-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLinkedStack.java
More file actions
58 lines (47 loc) · 1.12 KB
/
LinkedStack.java
File metadata and controls
58 lines (47 loc) · 1.12 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
package generics;
/**
* RUN:
* javac generics/LinkedStack.java && java generics.LinkedStack
* OUTPUT:
* stun!
* on
* Phases
*/
public class LinkedStack<T> {
private static class Node<U> {
U item;
Node<U> next;
Node() {
item = null;
next = null;
}
Node(U item, Node<U> next) {
this.item = item;
this.next = next;
}
boolean end() {
return item == null && next == null;
}
}
private Node<T> top = new Node<T>(); // end sentinel !!!
public void push(T item) {
top = new Node<T>(item, top);
}
public T pop() {
T result = top.item;
if (! top.end()) {
top = top.next;
}
return result;
}
public static void main(String[] args) {
LinkedStack<String> lss = new LinkedStack<String>();
for (String s : "Phases on stun!".split(" ")) {
lss.push(s);
}
String s;
while((s = lss.pop()) != null) {
System.out.println(s);
}
}
}