-
Notifications
You must be signed in to change notification settings - Fork 20
/
StackArrayList.java
106 lines (92 loc) · 2.44 KB
/
StackArrayList.java
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
99
100
101
102
103
104
105
106
import java.util.ArrayList;
import java.util.EmptyStackException;
/**
* Stack implementation using ArrayList.
*/
public class StackArrayList {
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
StackArrayList stack = new StackArrayList();
assert stack.isEmpty();
// Push elements to the top of this stack.
for (int i = 1; i <= 5; ++i) {
stack.push(i);
assert stack.size() == i;
}
assert stack.size() == 5;
assert stack.peek() == 5 && stack.pop() == 5 && stack.peek() == 4;
// Pop elements from the top of this stack until it is empty.
while (!stack.isEmpty()) {
stack.pop();
}
assert stack.isEmpty();
try {
stack.pop();
assert false;
// Should not reach here
} catch (EmptyStackException e) {
assert true;
}
}
// ArrayList to store stack elements.
private ArrayList<Integer> stack;
/**
* Constructor
*/
public StackArrayList() {
stack = new ArrayList<>();
}
/**
* Pushes an item onto the top of this stack.
*
* @param value the item to be pushed onto this stack.
*/
public void push(int value) {
stack.add(value);
}
/**
* Removes the element at the top of this stack and returns that element.
*
* @return top of this stack.
* @throws EmptyStackException if this stack is empty.
*/
public int pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
// Remove last element from stack.
return stack.remove(stack.size() - 1);
}
/**
* Tests if this stack is empty.
*
* @return true if this stack is empty; false otherwise.
*/
public boolean isEmpty() {
return stack.isEmpty();
}
/**
* Returns the element at the top of this stack without removing it from the stack.
*
* @return top of this stack.
* @throws EmptyStackException if this stack is empty.
*/
public int peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.get(stack.size() - 1);
}
/**
* Returns the number of elements in this stack.
*
* @return size of this stack.
*/
public int size() {
return stack.size();
}
}