DSA :Stack implementation using Linked List
package javaapplication7;
import java.io.*;
import java.lang.*;
class node
{ int data;
node prev,next;
node(int n)throws Exception
{
next=null;
prev=null;
data=n;
}
void display()throws Exception
{
System.out.println(data);
}
}
class stack
{
node top=null;
void push(int dd)throws Exception
{
node n1=new node(dd);
if(top==null)
top=n1;
else
{
top.next=n1;
n1.prev=top;
top=n1;
}
}
node pop()throws Exception
{
node item;
if(top==null)
{
item=top;
System.out.println("STACK IS EMPTY");
}
else if(top.prev==null)
{
item=top;
top=null;
}
else
{
item=top;
top=top.prev;
top.next=null;
}
return item;
}
void display()throws Exception
{
System.out.println("STACK IS...");
node current=top;
while(current!=null)
{
System.out.println(current.data);
current=current.prev;
}
}
}
class javaapplication7
{
public static void main(String[] args)throws Exception
{
int t;
stack s=new stack();
do{
System.out.println(" enter your choice \n1.push\n2.pop\n 3 display \t");
InputStreamReader isr1=new InputStreamReader(System.in);
BufferedReader br1=new BufferedReader(isr1);
int op=Integer.parseInt(br1.readLine());
switch(op)
{
case 1:System.out.println("enter the element to be pushed");
InputStreamReader isr2=new InputStreamReader(System.in);
BufferedReader br2=new BufferedReader(isr2);
int j=Integer.parseInt(br2.readLine());
s.push(j);
break;
case 2:
node nn=s.pop();
if(nn!=null)
System.out.println(nn.data+"is poped out");
break;
case 3:s.display();
break;
default:System.out.println("INVALID OPTION");
}
System.out.println("do you want to continue \n1=>yes \n0=>no");
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
t=Integer.parseInt(br.readLine());
}while(t==1);
}
}
No comments:
Post a Comment