import java.io.*;
class Node
{
public int item;
public Node next;
public Node(int val)
{
item = val;
}
}
class LinkedList
{
private Node first;
public LinkedList()
{
first = null;
}
public void push(int val)
{
Node newNode = new Node(val);
newNode.next = first;
first = newNode;
}
public int pop()
{
if(first==null)
{
System.out.println("Stack is Empty");
return 0;
}
else
{
int temp = first.item;
first = first.next;
return temp;
}
}
public void display()
{
if(first==null)
{
System.out.println("Stack is Empty");
}
else
{
System.out.println("Elements from top to bottom");
Node current = first;
while(current != null)
{
System.out.println("[" + current.item + "] ");
current = current.next;
}
System.out.println("");
}
}
}
class StackLinkedList
{
public static void main(String[] args) throws IOException
{
LinkedList ll = new LinkedList();
System.out.println("1.PUSH\n2.POP\n3.DISPLAY");
while(true)
{
System.out.println("Enter the Key of the Operation");
int c=Integer.parseInt((new BufferedReader(new InputStreamReader(System.in))).readLine());
switch(c)
{
case 1:
System.out.println("Enter the Element");
int val=Integer.parseInt((new BufferedReader(new InputStreamReader(System.in))).readLine());
ll.push(val);
break;
case 2:
int temp=ll.pop();
if(temp!=0)
System.out.println("Element popped is [" + temp + "] ");
break;
case 3:
ll.display();
break;
case 4:
System.exit(0);
default:
System.out.println("You have entered invalid Key.\n Try again");
}
}
}
}
No comments:
Post a Comment