Repository navigation
Expand file tree
/
Copy pathLinkedStack.java
More file actions
98 lines (82 loc) · 2.05 KB
/
Copy pathLinkedStack.java
File metadata and controls
98 lines (82 loc) · 2.05 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
87
88
89
90
91
92
93
94
95
96
97
98
import static njupt.yyz.Print.*;
import java.util.*;
public class LinkedStack<Item> implements Iterable<Item> {
private Node first;
private int N;
private class Node {
Item item;
Node next;
}
public boolean isEmpty(){
return 0 == N;
}
public int size(){
return N;
}
public void push(Item item){
Node oldfirst = first;
first = new Node();
first.item = item;
first.next =oldfirst;
N++;
}
public Item pop(){
if(null == first){
throw new NullPointerException();
}
Item item = first.item;
first = first.next;
N--;
return item;
}
public String toString(){
if(isEmpty()){
return "[]";
}
String result = "[";
Node current;
for(current = first; current.next != null; current = current.next){
result += current.item + "->";
}
result += current.item + "]";
return result;
}
public Iterator<Item> iterator(){
return new LinkedIterator();
}
private class LinkedIterator implements Iterator<Item> {
private Node node = first;
public boolean hasNext(){
return node != null;
}
public Item next(){
Item a = node.item;
node = node.next;
return a;
}
public void remove(){
throw new UnsupportedOperationException();
}
}
public static void main(String[] args){
Scanner s = new Scanner(System.in);
LinkedStack<String> stack = new LinkedStack<String>();
String token;
while(true){
token = s.nextLine();
if(token.equals("exit")){
break;
}
if(token.equals("-")){
stack.pop();
}
else{
stack.push(token);
}
println(stack);
}
for(String str : stack){
print(str + " ");
}
}
}