-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFixedCapacityStack.java
More file actions
50 lines (40 loc) · 1.02 KB
/
Copy pathFixedCapacityStack.java
File metadata and controls
50 lines (40 loc) · 1.02 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
/*
* Sample usage: java FixedCapacityStack < tobe.txt
*/
public class FixedCapacityStack<Item> {
private Item[] a; //stack entries
private int N; // size
public FixedCapacityStack(int cap){
a = (Item[]) new Object[cap];
}
public boolean isEmpty(){
return N==0;
}
public int size(){
return N;
}
public void push(Item item){
// Add item to top of the stack
a[N] = item;
N++;
}
public Item pop(){
// Remove item from top of the stack
N--;
return a[N];
}
public static void main(String[] args){
FixedCapacityStack<String> s;
s = new FixedCapacityStack<String>(100);
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)");
}
}