2.9 KiB
2.9 KiB
Write a Java method pop() for a stack implemented using an array.
public class Stack {
private int[] stackArray; // Array to hold stack elements
private int top; // Index of the top element
private int capacity; // Maximum capacity of the stack
// Constructor to initialize the stack
public Stack(int size) {
stackArray = new int[size];
capacity = size;
top = -1; // Indicates the stack is empty
}
// Method to add an element to the stack
public void push(int item) {
if (isFull()) {
throw new RuntimeException("Stack overflow");
}
stackArray[++top] = item; // Increment top and store the item
}
// Method to remove and return the top element of the stack
public int pop() {
if (isEmpty()) {
throw new RuntimeException("Stack underflow");
} return stackArray[top--]; // Return the top element and decrement top
}
// Method to check if the stack is empty
public boolean isEmpty() {
return top == -1;
}
// Method to check if the stack is full
public boolean isFull() {
return top == capacity - 1;
}
// Method to view the top element without removing it
public int peek() {
if (isEmpty()) {
throw new RuntimeException("Stack is empty");
} return stackArray[top];
}
public static void main(String[] args) {
Stack stack = new Stack(5); // Create a stack with capacity 5
// Example usage
stack.push(10);
stack.push(20);
stack.push(30);
System.out.println(stack.pop()); // Output: 30
System.out.println(stack.pop()); // Output: 20
System.out.println(stack.pop()); // Output: 10
}
}
Explanation:
- Array Storage: The stack elements are stored in an array (
stackArray
). - Pointer: The
top
variable keeps track of the current top of the stack. - Pop Operation: The
pop()
method checks if the stack is empty using theisEmpty()
method. If not, it returns the element at thetop
index and decrementstop
. - Edge Cases:
- Underflow: If the stack is empty, it throws a
RuntimeException
. - Overflow: The
push()
method checks for overflow before adding elements.
- Underflow: If the stack is empty, it throws a
This ensures a robust implementation of the pop()
operation.
- The expression
stackArray[top--]
first retrieves the value atstackArray[top]
and then decrementstop
by 1. - This uses the post-decrement operator (
--
), which means:- The value of
top
is used to access the current top element. - After accessing the value,
top
is decremented.
- The value of
Why top
Controls the Stack?
The value of top
acts as a pointer to the last valid element in the stack. By decrementing it, you effectively "remove" the topmost element from the stack, even though the value remains in the array until overwritten by a push()
operation.
Conclusion:
Yes, calling pop()
does update top
, which is crucial for maintaining the stack's state. This is a standard approach for implementing a stack using an array.