-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.java
94 lines (76 loc) · 1.99 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Stack<Key> implements Iterable<Key> {
private Node<Key> first;
private Node<Key> last;
private int n = 0;
private static class Node<Item> {
private Item item;
private Node<Item> prev;
}
public boolean isEmpty() {
return first == null;
}
public void push(Key item) {
Node<Key> oldLast = last;
last = new Node<Key>();
last.item = item;
if (isEmpty()) first = last;
else {
last.prev = oldLast;
}
n++;
}
public Key pop() {
if (last == null) return null;
Key item = last.item;
last = last.prev;
n--;
return item;
}
public Iterator<Key> iterator() {
return new LinkedIterator(last);
}
// an iterator, doesn't implement remove() since it's optional
private class LinkedIterator implements Iterator<Key> {
private Node<Key> current;
public LinkedIterator(Node<Key> last) {
current = last;
}
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Key next() {
if (!hasNext()) throw new NoSuchElementException();
Key item = current.item;
current = current.prev;
return item;
}
}
public String toString() {
String out = "";
Iterator itr = iterator();
while (itr.hasNext()) {
out += ", " + itr.next();
}
return "[" + out.substring(2, out.length()) + "]";
}
public static void main(String[] args) {
System.out.println("***");
Stack<Integer> stack = new Stack<>();
stack.push(3);
stack.push(5);
stack.push(7);
stack.push(10);
stack.pop();
stack.pop();
stack.push(100);
for (int x: stack) {
System.out.println(x);
}
System.out.println(stack.toString());
}
}