-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.java
54 lines (43 loc) · 1.21 KB
/
Stack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* A linked list implementation of a stack
*
* @author William Fiset, william.alexandre.fiset@gmail.com
*/
public class Stack<T> implements Iterable<T> {
private java.util.LinkedList<T> list = new java.util.LinkedList<T>();
// Create an empty stack
public Stack() {}
// Create a Stack with an initial element
public Stack(T firstElem) {
push(firstElem);
}
// Return the number of elements in the stack
public int size() {
return list.size();
}
// Check if the stack is empty
public boolean isEmpty() {
return size() == 0;
}
// Push an element on the stack
public void push(T elem) {
list.addLast(elem);
}
// Pop an element off the stack
// Throws an error is the stack is empty
public T pop() {
if (isEmpty()) throw new java.util.EmptyStackException();
return list.removeLast();
}
// Peek the top of the stack without removing an element
// Throws an exception if the stack is empty
public T peek() {
if (isEmpty()) throw new java.util.EmptyStackException();
return list.peekLast();
}
// Allow users to iterate through the stack using an iterator
@Override
public java.util.Iterator<T> iterator() {
return list.iterator();
}
}