-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListStack.java
More file actions
86 lines (56 loc) · 1.26 KB
/
ListStack.java
File metadata and controls
86 lines (56 loc) · 1.26 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
82
83
84
85
86
package Stack.src;
import java.util.Iterator;
/**
* 使用链表实现的栈
*/
public class ListStack<Item> implements MyStack<Item> {
private Node top = null;
private int N = 0;
private class Node {
Item item;
Node next;
}
@Override
public MyStack<Item> push(Item item) {
Node newTop = new Node();
newTop.item = item;
newTop.next = top;
top = newTop;
N++;
return this;
}
@Override
public Item pop() throws Exception {
if (isEmpty()) {
throw new Exception("stack is empty");
}
Item item = top.item;
top = top.next;
N--;
return item;
}
@Override
public boolean isEmpty() {
return N == 0;
}
@Override
public int size() {
return N;
}
@Override
public Iterator<Item> iterator() {
return new Iterator<Item>() {
private Node cur = top;
@Override
public boolean hasNext() {
return cur != null;
}
@Override
public Item next() {
Item item = cur.item;
cur = cur.next;
return item;
}
};
}
}