import java.util.
*;
class Stack {
public int capacity;
public int top = -1;
public int[] a;
Scanner sc = new Scanner(System.in);
public Stack(int capacity) {
this.capacity = capacity;
a = new int[capacity];
}
public int size() {
return (top + 1);
}
public boolean isEmpty() {
return (top == -1);
}
public boolean isFull() {
return (size() == capacity);
}
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty!");
return -1; // Return a default value or signal an error condition.
}
return a[top];
}
public void push(int data) {
if (isFull()) {
System.out.println("Stack Overflow!");
} else {
top++;
a[top] = data;
}
}
public int pop() {
if (isEmpty()) {
System.out.println("Stack Underflow!");
return -1; // Return a default value or signal an error condition.
} else {
int temp = top;
top--;
return a[temp];
}
}
public void display() {
int i = top;
while (i >= 0) {
System.out.print(a[i] + " ");
i--;
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter size of stack");
int capacity = sc.nextInt();
Stack stack = new Stack(capacity);
while (true) {
System.out.println("1. Push 2. Pop 3. Peek 4. Display 5. Exit");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Enter element to push:");
int data = sc.nextInt();
stack.push(data);
break;
case 2:
int popped = stack.pop();
if (popped != -1) {
System.out.println("Popped element: " + popped);
}
break;
case 3:
int peeked = stack.peek();
if (peeked != -1) {
System.out.println("Peeked element: " + peeked);
}
break;
case 4:
stack.display();
break;
case 5:
System.exit(0);
default:
System.out.println("Invalid choice!");
}
}
}
}