-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray Stack
More file actions
68 lines (55 loc) · 1.76 KB
/
Array Stack
File metadata and controls
68 lines (55 loc) · 1.76 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
package DataS;
public class Array_Stack {
static class ArrayStack {
private int[] stack;
private int size;
private int capacity;
public ArrayStack(int initialCapacity) {
stack = new int[initialCapacity];
capacity = initialCapacity;
size = 0;
}
public void push(int x) {
if (size == capacity) {
resize();
}
stack[size++] = x;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
int poppedElement = stack[--size];
return poppedElement;
}
public int top() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
}
return stack[size - 1];
}
public boolean isEmpty() {
return size == 0;
}
private void resize() {
int newCapacity = 2 * capacity;
int[] newStack = new int[newCapacity];
System.arraycopy(stack, 0, newStack, 0, capacity);
capacity = newCapacity;
stack = newStack;
}
}
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(2);
stack.push(5);
stack.push(12);
stack.push(20);
System.out.println("Top element: " + stack.top());
System.out.println("Popped element: " + stack.pop());
System.out.println("Top element after pop: " + stack.top());
System.out.println("Is stack empty? " + stack.isEmpty());
stack.pop();
stack.pop();
System.out.println("Is stack empty after popping all elements? " + stack.isEmpty());
}
}