Linked List Stack

import java.io.*;
class Node
{
int info;
Node nptr;
static Node top;

public static void main()throws IOException
{
InputStreamReader x=new InputStreamReader(System.in);
BufferedReader y=new BufferedReader(x);
int e,choice,flag;
top = new Node();
top=null;

do
{
System.out.println(” \f 1. Push \n 2. Pop \n 3. Display \n 4. Exit”);
choice = Integer.parseInt(y.readLine());

switch(choice)
{
case 1: System.out.println(“Element”);
e=Integer.parseInt(y.readLine());
Node current = new Node();
current=current.createNode(e);
current.pushNode(current);
break;
case 2:
top.popNode();
break;
case 3:
top.displayNodes();
break;

case 4: System.out.println(“Quitting…”);
System.exit(0);

default:
System.out.println(“Wrong choice…”);

}

System.out.println(“Enter: 1 to continue, 0 to terminate”);
flag = Integer.parseInt(y.readLine());

} while(flag==1);

}

public Node createNode(int e)
{
Node temp = new Node();
temp.info = e;
temp.nptr = null;
return temp;
}

public void pushNode(Node nd)
{
if(top==null)
top=nd;

else
{
nd.nptr=top;
top=nd;
}

}

public void displayNodes()
{
if(top==null)
System.out.println(“Stack Empty…”);

else
{
Node copy = top;
System.out.println(“The elements of the stack are :”);
while(copy!=null)
{
System.out.println(copy.info);
copy=copy.nptr;
}
}
}

public void popNode()
{
if(top==null)
System.out.println(“Stack underflow…”);

else
{
System.out.println(“Element “+ top.info +” has been popped out…”);
top=top.nptr;
}

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s