-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
81 lines (76 loc) · 1.34 KB
/
Stack.java
File metadata and controls
81 lines (76 loc) · 1.34 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
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
import java.util.Iterator;
public class Stack<T> implements Iterable<T>{
class Node{
T item;
Node next;
}
private Node first, last;
private int N = 0; // count;
public Stack(){}
public Stack(Stack<T> that){
for(Iterator<T> it = that.iterator(); it.hasNext();){
this.push(it.next());
}
}
T peek(){
if(last == null) throw new IllegalStateException();
return last.item;
}
void push(T item){
if(N == 0){
first = new Node();
first.item = item;
last = first;
}
else if(N == 1){
last = new Node();
last.item = item;
first.next = last;
}
else{
last.next = new Node();
last.next.item = item;
last = last.next;
}
N++;
}
T pop(){
T ret;
if(N == 0) throw new NullPointerException();
else if(N == 1){
ret = first.item;
first = last = null;
}
else if(N == 2){
ret = last.item;
last = first;
}
else{
ret = last.item;
Node current = first;
while(current.next != last){
current = current.next;
}
last = current;
}
N--;
return ret;
}
int getSize(){
return N;
}
public Iterator<T> iterator() {
return new StackIterator();
}
private class StackIterator implements Iterator<T>{
Node curNode = first;
public boolean hasNext() {
return curNode != null;
}
public T next() {
T ret = curNode.item;
curNode = curNode.next;
return ret;
}
}
}