- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack.java
More file actions
Latest commit
54 lines (43 loc) · 1.21 KB
/
Copy pathStack.java
File metadata and controls
54 lines (43 loc) · 1.21 KB
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
*/
publicclassStack<T> implementsIterable<T> {
privatejava.util.LinkedList<T> list = newjava.util.LinkedList<T>();
// Create an empty stack
publicStack() {}
// Create a Stack with an initial element
publicStack(TfirstElem) {
push(firstElem);
}
// Return the number of elements in the stack
publicintsize() {
returnlist.size();
}
// Check if the stack is empty
publicbooleanisEmpty() {
returnsize() == 0;
}
// Push an element on the stack
publicvoidpush(Telem) {
list.addLast(elem);
}
// Pop an element off the stack
// Throws an error is the stack is empty
publicTpop() {
if (isEmpty()) thrownewjava.util.EmptyStackException();
returnlist.removeLast();
}
// Peek the top of the stack without removing an element
// Throws an exception if the stack is empty
publicTpeek() {
if (isEmpty()) thrownewjava.util.EmptyStackException();
returnlist.peekLast();
}
// Allow users to iterate through the stack using an iterator
@Override
publicjava.util.Iterator<T> iterator() {
returnlist.iterator();
}
}