-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicStack.java
More file actions
70 lines (54 loc) · 1.67 KB
/
DynamicStack.java
File metadata and controls
70 lines (54 loc) · 1.67 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
67
68
69
70
public class DynamicStack {
int capacity = 2; // Set the starting capacity of the stack
int[] stack = new int[capacity]; // Initialise stack (array)
int top = 0; // Track top of stack
private void expand() {
int length = size();
int[] newStack = new int[capacity * 2];
System.arraycopy(stack, 0, newStack, 0, length);
stack = newStack;
capacity *= 2;
}
private void shrink() {
int length = size();
if (length <= (capacity / 4)) { // If the length of the stack is 1/4 the size of the capacity, half the capacity
capacity = capacity / 2;
int newStack[] = new int[capacity];
System.arraycopy(stack, 0, newStack, 0, length); // Copy old array into new array
stack = newStack; // Reassign array
}
}
public void push(int data) { // Push to the top of stack
if (size() == capacity) { // If stack is full
expand();
}
stack[top] = data; // Add value to stack
top++;
}
public int pop() { // Remove top value from stack
if (isEmpty()) { // If stack is empty
System.out.println("STACK IS EMPTY");
return 0;
} else {
top--;
int data = stack[top];
stack[top] = 0;
shrink();
return data;
}
}
public int peek() {
return stack[top - 1];
}
public void show() {
for (int i = 0; i < stack.length; i++) {
System.out.print(stack[i] + " ");
}
}
public int size() {
return top;
}
public boolean isEmpty() {
return top <= 0;
}
}