class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
class Stack {
private Node top;
Stack() {
this.top = null;
}
// Push operation
public void push(int data) {
Node newNode = new Node(data);
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
System.out.println("Pushed " + data);
}
// Pop operation
public int pop() {
if (top == null) {
System.out.println("Stack is empty");
return -1;
} else {
int poppedData = top.data;
top = top.next;
System.out.println("Popped " + poppedData);
return poppedData;
}
}
// Display operation
public void display() {
if (top == null) {
System.out.println("Stack is empty");
} else {
Node temp = top;
System.out.print("Stack elements: ");
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
public static void main(String[] args) {
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
int choice, data;
do {
System.out.println("\nStack Operations:");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter data to push: ");
data = scanner.nextInt();
stack.push(data);
break;
case 2:
stack.pop();
break;
case 3:
stack.display();
break;
case 4:
System.out.println("Exiting...");
break;
default:
System.out.println("Invalid choice, please try again.");
}
} while (choice != 4);
scanner.close();
}
}
0 Comments