A stack has been implemented using an array. The user can perform various stack operations, such as pushing an element, popping an element, displaying elements, checking if the stack is empty, and exiting. and Here, the user needs to specify the size of the stack.
import java.util.Scanner;
class StackArray {
private int[] stack;
private int top;
private int size;
// Constructor
StackArray(int size) {
this.size = size;
stack = new int[size];
top = -1;
}
// Push operation
void push(int value) {
if (top == size - 1) {
System.out.println("Stack Overflow! Element insert nahi ho sakta.");
} else {
stack[++top] = value;
System.out.println(value + " stack me push ho gaya.");
}
}
// Pop operation
void pop() {
if (top == -1) {
System.out.println("Stack Underflow! Stack khaali hai.");
} else {
System.out.println(stack[top--] + " stack se pop ho gaya.");
}
}
// Peek operation
void peek() {
if (top == -1) {
System.out.println("Stack khaali hai, koi top element nahi.");
} else {
System.out.println("Top element: " + stack[top]);
}
}
// Check empty
void isEmpty() {
System.out.println(top == -1 ? "Stack khaali hai." : "Stack khaali nahi hai.");
}
// Display stack
void display() {
if (top == -1) {
System.out.println("Stack khaali hai.");
} else {
System.out.print("Stack elements: ");
for (int i = 0; i <= top; i++) {
System.out.print(stack[i] + " ");
}
System.out.println();
}
}
}
public class Stack_Using_Array_With_User_Input {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Stack ka size enter kijiye: ");
int size = sc.nextInt();
StackArray stack = new StackArray(size);
while (true) {
System.out.println("\n1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. IsEmpty");
System.out.println("5. Display");
System.out.println("6. Exit");
System.out.print("Choice enter kijiye: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Value enter kijiye: ");
int val = sc.nextInt();
stack.push(val);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.isEmpty();
break;
case 5:
stack.display();
break;
case 6:
System.out.println("Program exit ho raha hai.");
sc.close();
return;
default:
System.out.println("Invalid choice!");
}
}
}
}
A stack has been implemented using the Stack class from the Java Collections Framework. Users can perform various operations, such as pushing elements, popping elements, displaying elements, searching element and exiting. The stack size is unlimited, allowing users to add any number of elements or data items to it.