Program : Stack Using Linked List
import java.io.*; //To implement I/O operations
class link
{
int data; //data item
link next; //next link in list
link(int id) //constructor
{
data=id; //initialize data
}
void displaylink() //To display the list
{
System.out.println("{"+data+"}");
}
} //end of class link
class stack
{
link first; //ref to first link on list
stack() //constructor
{
first=null; //no links on list yet
}
public void insert(int dd) //To insert into the list
{
link op=new link(dd); //make new link
op.next=first;
first=op;
} //End of function create
void delete() //To delete node from the list
{
if (first==null) //Check if stack is empty
{
System.out.println("STACK EMPTY");
//Print stack Empty
}
else
{
first=first.next; //point to next node
System.out.println("THE TOP ELEMENT IS DELETED FROM STACK");
}
} //End of function delete
void display() //To display the stack
{
link current=first; //start at the beginning of the list
System.out.println("THE ELEMENTS OF STACK ARE");
while (current!=null) //until end of the list
{
current.displaylink();
//print data
current=current.next;
//move to next link
}
} //end of function display
} //End of class stack
public class Stacklink //The main class linkstack
{
public static void main(String args[])throws IOException
//main function
{
stack m=new stack(); //make new linklist
char cc;
try
{
do
{
BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
System.out.println("MENU");
//Print menu
System.out.println("1.PUSH");
System.out.println("2.POP");
System.out.println("3.DISPLAY");
System.out.println("ENTER YOUR CHOICE");
int y=Integer.parseInt(f.readLine());
//Accepts choice
if (y==1)
{
System.out.println("ENTER THE ELEMENT TO BE INSERTED");
int a=Integer.parseInt(f.readLine());
m.insert(a); //Assign values to links
}
if(y==2)
m.delete(); //Call the function delete
if (y==3)
m.display(); //Call the function display
System.out.println();
System.out.println("DO YOU WANT TO CONTINUE(Y/N)");
cc=(char)f.read();
}
while((cc=='y')||(cc=='Y'));
} //End of try statement
catch(Exception e) //To catch any exceptions
{
}
} //End of main function
} //End of main class linkstack
0 comments:
Post a Comment