-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackArray.java
More file actions
66 lines (50 loc) · 1.48 KB
/
StackArray.java
File metadata and controls
66 lines (50 loc) · 1.48 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package Stack;
import java.util.EmptyStackException;
public class StackArray {
private Employee[] stack;
private int top;
public StackArray(int capacity) {
stack = new Employee[capacity];
}
public void push(Employee employee) {
// Worse case for stack made with an array is O(n) for having to resize
// and copy the old array into the new one
if (top == stack.length) {
// resize array
Employee[] newArray = new Employee[2 * stack.length];
// Copy array into new array
System.arraycopy(stack, 0, newArray, 0, stack.length);
// Assign new array to stack
stack = newArray;
}
// If no resize is need push is O(1)
stack[top++] = employee;
}
public Employee pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
// Make top the index of the previous item
Employee employee = stack[--top];
// Set top to null to delete the top most item
stack[top] = null;
return employee;
}
public Employee peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack[top - 1];
}
public int size() {
return top;
}
public boolean isEmpty() {
return top == 0;
}
public void printStack() {
for (int i = top - 1; i >= 0; i--) {
System.out.println(stack[i]);
}
}
}