1. Introduction
A Stack is a linear data structure that follows the Last In First Out (LIFO) principle, meaning the last element added to the stack will be the first one to be removed. Common operations on a stack include push (to add an item) and pop (to remove the top item). One simple way to implement a stack is by using an array. In this blog post, we’ll demonstrate how to create a stack using an array in Java.
2. Program Steps
1. Define the structure of the Stack using an array.
2. Implement the following primary stack operations:
– push: To add an element to the top of the stack.
– pop: To remove and return the top element from the stack.
– peek: To view the top element without removing it.
– isEmpty: To check if the stack is empty.
3. Test the stack operations in the main function.
3. Code Program
class Stack {
private int maxSize;
private int top;
private int[] stackArray;
public Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1; // Stack is empty
}
public void push(int value) {
if (top < maxSize - 1) {
stackArray[++top] = value; // Increment top and insert value
} else {
System.out.println("Stack is full. Cannot push " + value);
}
}
public int pop() {
if (top >= 0) {
return stackArray[top--]; // Return top value and decrement top
} else {
System.out.println("Stack is empty. Cannot pop.");
return -1; // Representing an empty stack condition
}
}
public int peek() {
if (top >= 0) {
return stackArray[top];
} else {
System.out.println("Stack is empty. Nothing to peek.");
return -1; // Representing an empty stack condition
}
}
public boolean isEmpty() {
return (top == -1);
}
public static void main(String[] args) {
Stack stack = new Stack(3);
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40); // Should print an error message
System.out.println("Top element: " + stack.peek());
System.out.println("Popped element: " + stack.pop());
System.out.println("Is stack empty? " + stack.isEmpty());
}
}
Output:
Stack is full. Cannot push 40 Top element: 30 Popped element: 30 Is stack empty? false
4. Step By Step Explanation
1. The Stack class encapsulates the structure and operations of our array-based stack.
2. maxSize represents the maximum size of the stack. top is an index that keeps track of the top-most element in the stack, and stackArray is the array that stores the stack elements.
3. The push method adds an element to the top of the stack, but before doing so, it checks if there's space left.
4. The pop method returns the top-most element from the stack and decreases the top index.
5. The peek method lets you see the top-most element without removing it.
6. The isEmpty method checks if the stack is empty.
7. In the main method, we create a Stack of size 3, push three integers, and then try to push a fourth one which results in an error message. After that, we peek at the top-most element, pop it, and finally check if the stack is empty, resulting in the provided output.