Wednesday 22 May 2013

43. QUEUE USING LINKED LIST

Code:
import java.util.Scanner;

public class Node
{
    int info;
    Node next,prev;
    Node left,right;
}

public class QueueLL
{
    Node start=new Node();
    Node end=new Node();
    Node curr=new Node();
    int ch,num;
    Object obj=new Object();

    QueueLL()
    {
        start=null;
        end=null;
        num=0;
    }

    void Add(int val)
    {

        Node t=new Node();
        t.info=val;
        if(num++==0)
            start=t;
        else
           t.next=end;
        end=t;
    }

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

    void Display()
    {
        curr=end;
        System.out.print("Back -> ");
        while(curr!=null)
        {
            System.out.print(curr.info + " -> ");
            curr=curr.next;
        }
        System.out.println("Front");
    }

    public static void main(String args[])
    {
        int ch,val;
        QueueLL q=new QueueLL();
        Scanner in = new Scanner(System.in);
        while(true)
        {
            System.out.println("Enter your Choice");

            System.out.println("-------------------------------------");
            System.out.println("1 : Add\t2 : Del\t3 : Display\t4 : Exit");
            ch=in.nextInt();
            switch(ch)
            {
                case 1:
                {
                    System.out.print("Enter a Number = ");
                    val=in.nextInt();
                    q.Add(val);
                    break;
                }
                case 2:
                {
                    q.Del();
                    break;
                }
                case 3:
                {
                    q.Display();
                    break;
                }
                case 4:
                    System.exit(0);
                    break;
                default : continue;
            }
        }
    }

}

Need the code??

No comments:

Post a Comment