Stack based on Linked List in Java

Write a program in Java to implement a Stack on a Linked List.

The program should be able to perform the following operations:

  • Push: To insert an element into the stack.
  • Pop: To delete an element from the stack.
  • Display: To display the content of the stack.
  • Peek: To display the topmost element in the stack.

 

import java.io.*;
class Node{
    int data;
    Node next;
    public Node(){
        data = 0;
        next = null;
    }
    public Node(int d){
        data = d;
        next = null;
    }
}
class LinkedStack{
    Node top;
    public LinkedStack(){
        top = null;
    }
    public void push(int d){
        Node n = new Node(d);
        if(top == null)
            top = n;
        else{
            n.next = top;
            top = n;
        }
        System.out.println(d + " pushed.");
    }
    public void pop(){
        if(top == null)
            System.out.println("Stack underflow!");
        else{
            int d = top.data;
            top = top.next;
            System.out.println(d + " popped.");
        }
    }
    public void display(){
        if(top == null)
            System.out.println("Stack is empty!");
        else{
            System.out.println("Stack contents:");
            Node n = top;
            while(n != null){
                System.out.print(n.data + "\t");
                n = n.next;
            }
            System.out.println();
        }
    }
    public void peek(){
        if(top == null)
            System.out.println("Stack is empty!");
        else
            System.out.println("Topmost element: " + top.data);
    }
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        LinkedStack stack = new LinkedStack();
        while(true){
            System.out.println("1. Push");
            System.out.println("2. Pop");
            System.out.println("3. Display");
            System.out.println("4. Peek");
            System.out.print("Enter your choice: ");
            int choice = Integer.parseInt(br.readLine());
            switch(choice){
                case 1:
                System.out.print("Data to push: ");
                int d = Integer.parseInt(br.readLine());
                stack.push(d);
                break;
                case 2:
                stack.pop();
                break;
                case 3:
                stack.display();
                break;
                case 4:
                stack.peek();
                break;
                default:
                System.out.println("Bye...");
                return;
            }
        }
    }
}