-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
55 lines (42 loc) · 923 Bytes
/
Stack.java
File metadata and controls
55 lines (42 loc) · 923 Bytes
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
import java.util.ArrayList;
public class Stack<AnyType> {
public static void main(String[] args) {
Stack<Integer> ints = new Stack<Integer>();
ints.push(4);
ints.push(5);
ints.push(6);
ints.printStack();
}
private int topOfStack;
private ArrayList<AnyType> stack;
public Stack() {
this.topOfStack = -1;
this.stack = new ArrayList<AnyType>();
}
private void assertNotEmpty() {
if (topOfStack < 0) {
throw new IndexOutOfBoundsException();
}
}
public void push(AnyType item) {
topOfStack++;
stack.add(item);
}
public AnyType pop() {
assertNotEmpty();
AnyType item = stack.get(topOfStack);
topOfStack--;
return item;
}
public AnyType peak() {
assertNotEmpty();
return stack.get(topOfStack);
}
private void printStack() {
System.out.println("-");
for (int i = topOfStack; i >= 0; i--) {
System.out.println(stack.get(i));
}
System.out.println("-");
}
}