-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathArrayStack.java
46 lines (38 loc) Β· 961 Bytes
/
ArrayStack.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
package Stack;
public class ArrayStack<E> implements IStack<E> {
private static final int CAPACITY = 1000;
private E[] data;
private int top = -1;
public ArrayStack() {
this(CAPACITY);
}
public ArrayStack(int capacity) {
data = (E[]) new Object[capacity];
}
@Override
public int size() {
return top + 1;
}
@Override
public boolean isEmpty() {
return top == -1;
}
@Override
public void push(E e) throws IllegalStateException {
if (size() == data.length) throw new IllegalStateException("Stack is full");
data[++top] = e;
}
@Override
public E pop() {
if (isEmpty()) return null;
E target = data[top];
data[top] = null; // dereference to help garbage collection
top--;
return target;
}
@Override
public E peek() {
if (isEmpty()) return null;
return data[top];
}
}