-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayStack.java
55 lines (43 loc) · 1.6 KB
/
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
47
48
49
50
51
52
53
54
55
/*
Implementing a Stack Class
push(e): Adds element e to the top of the stack.
pop( ): Removes and returns the top element from the stack (or null if the stack is empty). Additionally, a stack supports the following accessor methods for convenience:
top( ): Returns the top element of the stack, without removing it (or null if the stack is empty).
size( ): Returns the number of elements in the stack.
isEmpty( ): Returns a boolean indicating whether the stack is empty.
last update 2022 Dec 14
*/
public class ArrayStack<E> implements IStack<E> {
public static final int CAPACITY = 1000; // default array capacity
private E[] data; // generic array used for storage
private int m_index = −1; // index of the top element in stack
// constructs stack with default capacity
public ArrayStack( ) {
this(CAPACITY);
}
// constructs stack with given capacity
public ArrayStack(int capacity) {
data = (E[]) new Object[capacity]; // safe cast; compiler may give warning
}
public int size( ) {
return (m_index + 1);
}
public boolean isEmpty( ) {
return (m_index == −1);
}
public void push(E element) throws IllegalStateException {
if (size( ) == data.length) throw new IllegalStateException("Stack is full");
data[++m_index] = element; // increment t before storing new item
}
public E top( ) {
if (isEmpty( )) return null;
return data[m_index];
}
public E pop() {
if (isEmpty()) return null;
E answer = data[m_index];
data[m_index] = null; // dereference to help garbage collection
m_index−−;
return answer;
}
}