-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathArrayStack.java
58 lines (43 loc) · 1.18 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
56
57
58
package com.stacks;
import java.util.EmptyStackException;
public class ArrayStack {
private Student[] stack;
private int top;
ArrayStack(int capacity) {
stack = new Student[capacity];
}
public void push(Student student) { // time complexity -> O(n)
if (top == stack.length) {
// need to resize the backing array
Student[] newArray = new Student[2 * stack.length];
System.arraycopy(stack, 0, newArray, 0, stack.length);
stack = newArray;
}
stack[top++] = student;
}
public Student pop() { // time complexity -> O(1)
if (isEmpty()) {
throw new EmptyStackException();
}
Student student = stack[--top];
stack[top] = null;
return student;
}
public int size() {
return top;
}
public Student peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack[top - 1];
}
public boolean isEmpty() {
return top == 0;
}
public void printStack() {
for (int i = top - 1; i >= 0; i--) {
System.out.println(stack[i]);
}
}
}