-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResizingArrayStack.java
More file actions
85 lines (69 loc) · 1.85 KB
/
Copy pathResizingArrayStack.java
File metadata and controls
85 lines (69 loc) · 1.85 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
/*
* Sample usage: java ResizingArrayStack < tobe.txt
*/
import java.util.Iterator;
public class ResizingArrayStack<Item> implements Iterable<Item> {
private Item[] a = (Item[]) new Object[1]; //stack entries
private int N; // size
public boolean isEmpty(){
return N==0;
}
public int size(){
return N;
}
private void resize(int max){
// Move stack to a new array os size max.
Item[] temp = (Item[]) new Object[max];
for (int i = 0; i < N; i++){
temp[i] = a[i];
}
a = temp;
}
public void push(Item item){
// Add item to top of the stack
if (N == a.length){
resize(2*a.length);
}
a[N] = item;
N++;
}
public Item pop(){
// Remove item from top of the stack
N--;
Item item = a[N];
a[N] = null; // Avoid loitering
if (N > 0 && N == a.length/4){
resize(a.length/2);
}
return item;
}
public Iterator<Item> iterator(){
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item>{
// Support LIFO iteration
private int i = N;
public boolean hasNext(){
return i > 0;
}
public Item next(){
i--;
return a[i];
}
public void remove(){ }
}
public static void main(String[] args){
ResizingArrayStack<String> s;
s = new ResizingArrayStack<String>();
while (!StdIn.isEmpty()){
String item = StdIn.readString();
if (!item.equals("-")){
s.push(item);
}
else if (!item.isEmpty()){
StdOut.print(s.pop()+" ");
}
}
StdOut.println("("+s.size()+" left in stack)");
}
}