Evander Amorcillo
Programming Exercise # 6 - Stack Linked List
Code:
import java.util.Scanner;
class Node {
int data; // Integer data
Node next; // Pointer to the next node
}
class Stack {
private Node top;
public Stack() {
this.top = null;
}
// Push an element onto the stack
public void push(int x) {
Node node = new Node();
System.out.println("Inserting " + x);
node.data = x;
node.next = top;
top = node;
}
// Check if the stack is empty
public boolean isEmpty() {
return top == null;
}
// Peek at the top element of the stack
public int peek() {
if (!isEmpty()) {
return top.data;
} else {
System.out.println("The stack is empty");
return -1;
}
}
// Pop the top element from the stack
public void pop() {
if (top == null) {
System.out.println("Stack Underflow");
return;
}
System.out.println("Removing " + peek());
top = top.next;
}
// Display all elements in the stack
public void display() {
if (isEmpty()) {
System.out.println("The stack is empty");
return;
}
Node temp = top;
System.out.println("Stack elements are:");
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
int choice, value;
do {
System.out.println("\nStack Operations Menu:");
System.out.println("1. Push an element");
System.out.println("2. Pop an element");
System.out.println("3. Peek the top element");
System.out.println("4. Check if the stack is empty");
System.out.println("5. Display all elements");
System.out.println("6. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter the value to push: ");
value = scanner.nextInt();
stack.push(value);
break;
case 2:
stack.pop();
break;
case 3:
int topElement = stack.peek();
if (topElement != -1) {
System.out.println("The top element is: " + topElement);
}
break;
case 4:
if (stack.isEmpty()) {
System.out.println("The stack is empty");
} else {
System.out.println("The stack is not empty");
}
break;
case 5:
stack.display();
break;
case 6:
System.out.println("Exiting... Thank you!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
} while (choice != 6);
scanner.close();
}
}