class Stack {
private int[] stackArray;
private int top;
private static final int INITIAL_CAPACITY = 10;

// Constructor
public Stack() {
stackArray = new int[INITIAL_CAPACITY];
top = -1;
}

// Push an item onto the stack
public void push(int value) {
if (top == stackArray.length – 1) {
grow();
}
stackArray[++top] = value;
}

// Pop an item off the stack
public int pop() {
if (isEmpty()) {
throw new IllegalStateException(“Stack is empty”);
}
int value = stackArray[top–];
if (top < stackArray.length / 4) {
shrink();
}
return value;
}

// View the top item of the stack without popping it
public int peek() {
if (isEmpty()) {
throw new IllegalStateException(“Stack is empty”);
}
return stackArray[top];
}

// Check if the stack is empty
public boolean isEmpty() {
return top == -1;
}

// Grow the stack when it is full
private void grow() {
int newSize = stackArray.length * 2;
int[] newArray = new int[newSize];
System.arraycopy(stackArray, 0, newArray, 0, stackArray.length);
stackArray = newArray;
}

// Shrink the stack when it is too empty
private void shrink() {
int newSize = stackArray.length / 2;
if (newSize < INITIAL_CAPACITY) {
newSize = INITIAL_CAPACITY;
}
int[] newArray = new int[newSize];
System.arraycopy(stackArray, 0, newArray, 0, top + 1);
stackArray = newArray;
}

// finalize method to demonstrate cleanup
@Override
protected void finalize() throws Throwable {
try {
System.out.println(“Stack is being garbage collected”);
} finally {
super.finalize();
}
}
}

public class StackTest {
public static void main(String[] args) {
Stack stack = new Stack();

// Test pushing elements
stack.push(10);
stack.push(20);
stack.push(30);

// Test viewing the top element
System.out.println(“Top element: ” + stack.peek()); // Output: 30

// Test popping elements
System.out.println(“Popped element: ” + stack.pop()); // Output: 30
System.out.println(“Top element after pop: ” + stack.peek()); // Output: 20

// Test dynamic growth
for (int i = 0; i < 100; i++) {
stack.push(i);
}

// Test dynamic shrinkage
for (int i = 0; i < 100; i++) {
stack.pop();
}

// Test popping remaining elements
System.out.println(“Popped element: ” + stack.pop()); // Output: 20
System.out.println(“Popped element: ” + stack.pop()); // Output: 10

// Try to pop from an empty stack to see exception
try {
stack.pop();
} catch (IllegalStateException e) {
System.out.println(e.getMessage()); // Output: Stack is empty
}
}
}


Leave a Reply

Your email address will not be published. Required fields are marked *