Program to Implement Stack Structure in Java
Below is the implementation of Stack Structure in Java:
public class StackExample {
private int maxSize;
private int[] stackArray;
private int top;
public StackExample(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}
// Method to push an element onto the stack
public void push(int value) {
if (top == maxSize - 1) {
System.out.println("Stack overflow");
return;
}
stackArray[++top] = value;
System.out.println(value + " pushed into the stack");
}
// Method to pop an element from the stack
public int pop() {
if (top == -1) {
System.out.println("Stack underflow");
return -1;
}
int poppedElement = stackArray[top--];
System.out.println(poppedElement + " popped from the stack");
return poppedElement;
}
// Method to peek the top element of the stack
public int top() {
if (top == -1) {
System.out.println("Stack is empty");
return -1;
}
return stackArray[top];
}
// Method to check if the stack is empty
public boolean isEmpty() {
return (top == -1);
}
public static void main(String[] args) {
StackExample stack = new StackExample(5); // Creating a stack of size 5
// Pushing elements onto the stack
stack.push(10);
stack.push(20);
// Peeking the top element
System.out.println("Top element of the stack: " + stack.top());
// Popping elements from the stack
stack.pop();
stack.pop();
stack.pop(); // Trying to pop from an empty stack
// Checking if the stack is empty
System.out.println("Is stack empty? " + stack.isEmpty());
}
}
Output
10 pushed into the stack 20 pushed into the stack Top element of the stack: 20 20 popped from the stack 10 popped from the stack Stack underflow Is stack empty? true
Time and Space Complexity:
- The time complexity of the stack operations such as push, pop, peek, isEmpty and isFull and it can implemented using array is O(1).
- The Space Complexity of the array based implementation is O(n) where n is the maximum size of the stack.
Java Program to Implement Stack Data Structure
Stack is the fundamental Data Structure that can follow the Last In, First Out(LIFO) principle. It can work that the last element added to the stack will be the first one to be removed. It can operate like a stack of plates: We can only add or remove the topmost plate at any given time. The simplicity and efficiency of the stack make them crucial in various computer science applications.
In this article, we will learn about Stack Data Structure and How to Implement it in Java.