Saturday, April 16, 2011

Link-List with Stack


import java.util.Scanner;
public class StackLL
{
    Node start=new Node();
    Node top=new Node();
    Node curr=new Node();
    int ch,num;

    StackLL()
    {
        num=0;
        start=null;
        top=null;
    }

    void Push(int val)
    {
        Node t=new Node();
        t.info=val;
        t.next=null;
        if(num++==0)
            start=t;
        else
            top.next=t;
        top=t;

    }

    void Pop()
    {
        curr=start;
        if(num==0)
            System.out.println("Stack is Empty");
        else
        {
            if(top==start)
            {
                start=null;
                top=null;
                num=0;
            }
            else
            {
                while(curr.next!=top)
                    curr=curr.next;
                top=curr;
            }
        }
    }

    void Display()
    {
        curr=start;
        System.out.print("Bottom -> ");
        while(curr!=null)
        {
            System.out.print(curr.info + " -> ");
            curr=curr.next;
        }
        System.out.println("Top");
    }

    public static void main(String args[])
    {
        int ch,val;
        StackLL s=new StackLL();
        Scanner in = new Scanner(System.in);
        while(true)
        {
            System.out.println("\n-----------------------------------");
            System.out.println("Enter your Choice");
            System.out.println("1 : Push\t2 : Pop\t3 : Display\t4 : Exit");
            ch=in.nextInt();
            switch(ch)
            {
                case 1:
                {
                    System.out.print("Enter a Number = ");
                    val=in.nextInt();
                    s.Push(val);
                    break;
                }
                case 2:
                {
                    s.Pop();
                    break;
                }
                case 3:
                {
                    s.Display();
                    break;
                }
                case 4:
                    System.exit(0);
                    break;
                default : continue;
            }
        }
    }
}


No comments:

Post a Comment