Java program to implement stack data structure
www.theitroad.com
Sure, here's an example Java program to implement a stack data structure using an array:
public class Stack {
private int[] arr; // array to store the elements of the stack
private int top; // variable to keep track of the top of the stack
// constructor to create a stack of given size
public Stack(int size) {
arr = new int[size];
top = -1;
}
// method to push an element onto the stack
public void push(int element) {
if (top == arr.length - 1) {
System.out.println("Stack overflow");
} else {
arr[++top] = element;
}
}
// method to pop an element from the stack
public int pop() {
if (top == -1) {
System.out.println("Stack underflow");
return -1;
} else {
return arr[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 == arr.length - 1);
}
// method to peek at the top element of the stack without removing it
public int peek() {
if (top == -1) {
System.out.println("Stack is empty");
return -1;
} else {
return arr[top];
}
}
// main method to test the stack implementation
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
System.out.println("Top element of stack: " + stack.peek());
while (!stack.isEmpty()) {
System.out.println("Popped element: " + stack.pop());
}
System.out.println("Is stack empty? " + stack.isEmpty());
}
}
This program creates a stack of integers using an array, and provides methods to push and pop elements, check if the stack is empty or full, and peek at the top element without removing it. The main method demonstrates how to use the stack by pushing elements onto it, peeking at the top element, popping elements from the stack, and checking if the stack is empty.
