-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicArrayStack.java
More file actions
92 lines (74 loc) · 2.22 KB
/
Copy pathDynamicArrayStack.java
File metadata and controls
92 lines (74 loc) · 2.22 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package stackarray.src.stackusingarray;
import java.util.Arrays;
public class DynamicArrayStack {
private int[] stack;
private int size;
private int capacity;
public DynamicArrayStack(int initialCapacity) {
stack = new int[initialCapacity];
size = 0;
capacity = initialCapacity;
}
public void push(int value) {
if (size == capacity) {
resize();
}
stack[size++] = value;
}
public int pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty. Cannot pop element.");
}
int value = stack[--size];
stack[size] = 0; // Optional: Reset the popped element to 0
return value;
}
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty. Cannot peek element.");
}
return stack[size - 1];
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
private void resize() {
capacity *= 2;
stack = Arrays.copyOf(stack, capacity);
}
public void print() {
if (isEmpty()) {
System.out.println("Stack is empty.");
} else {
System.out.println("Stack elements: " + Arrays.toString(Arrays.copyOf(stack, size)));
}
}
public static void main(String[] args) {
DynamicArrayStack stack = new DynamicArrayStack(5);
try {
stack.push(10);
stack.push(20);
stack.push(30);
stack.print();
System.out.println("Peek: " + stack.peek());
stack.push(40);
stack.push(50);
stack.push(60); // This will trigger a resize
stack.print();
System.out.println("Pop: " + stack.pop());
stack.print();
System.out.println("Stack size: " + stack.size());
while (!stack.isEmpty()) {
System.out.println("Pop: " + stack.pop());
}
stack.print();
// This will throw an exception
stack.pop();
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}