Tuesday 21 August 2012

To implement stack using linked list.

/*Program For Stack using Linked List */ import java.io.*; import java.util.*; class Nodetype { int info; Nodetype next; Nodetype(int i) { info=i; next=null; } } //-------------------------------------------------------------------------------------------------------------- class Operations { Nodetype top=null; /*Where top is the pointer which will point to the element at the top of the stack hence it will act as the external pointer list.*/ void display( ) { /*display all elements of linked list*/ Nodetype temp; if(top==null) System.out.println("\nEmpty linked list"); else { System.out.print("Stack\n"); temp=top; while(temp!=null) { System.out.println(" "+temp.info); temp=temp.next; } } } void push(int x) { Nodetype node=new Nodetype(x); node.info=x; node.next=top; top=node; display(); }/*end push*/ //-------------------------------------------------------------------------------------------------------------- void pop() { Nodetype p=null; int x; p=top; if(p==null) { System.out.println("\nStack Underflow\n"); return; } System.out.print("\n\nThe element popped is "+p.info+"\n"); top=top.next; //display(); }/*end pop*/ //-------------------------------------------------------------------------------------------------------------- void stacktop() { if(top==null) { System.out.println("\nStack is empty\n"); return; } System.out.println("\nThe element at the top of the stack is "+top.info+"\n"); display(); }/*end stacktop*/ } //-------------------------------------------------------------------------------------------------------------- class LLStack { public static void main(String args[]) { Operations L =new Operations(); int i,j,n,c; Scanner src=new Scanner(System.in); System.out.println("Enter the number of elements to be pushed into stack:"); n=src.nextInt(); System.out.println("Enter the elements to be pushed:"); for(i=0;i<n;i++) { j=src.nextInt(); System.out.println("\n\nPush: " + j); L.push(j); } //L.display(); do { System.out.println("Do you wish to pop?(0/1)"); c=src.nextInt(); if (c==1) { L.pop(); L.stacktop(); } }while(c==1); L.display(); }/*end main*/ } ================================================================================================================== OUTPUT : C:\jdk1.6.0_16\bin>javac LLStack.java C:\jdk1.6.0_16\bin>java LLStack Enter the number of elements to be pushed into stack: 5 Enter the elements to be pushed: 9 Push: 9 Stack 9 8 Push: 8 Stack 8 9 7 Push: 7 Stack 7 8 9 6 Push: 6 Stack 6 7 8 9 5 Push: 5 Stack 5 6 7 8 9 Do you wish to pop?(0/1) 1 The element popped is 5 The element at the top of the stack is 6 Stack 6 7 8 9 Do you wish to pop?(0/1) 0 Stack 6 7 8 9 C:\jdk1.6.0_16\bin>javac LLStack.class

No comments:

Post a Comment