Sunday 16 December 2012

Queue implementation using Linked List in Java


import java.io.*;
class Node
{
public int item;
public Node next;
public Node(int val)
{
item = val;
}
}
class LinkedList
{
private Node front,rear;
public LinkedList()
{
front = null;
rear = null;
}
public void insert(int val)
{
Node newNode = new Node(val);
if (front == null) {
            front = rear = newNode;
        }
else {
            rear.next = newNode;
rear = newNode;
}
}
public int delete()
{
if(front==null)
{
System.out.println("Queue is Empty");
return 0;
}
else
{
int temp = front.item;
            front = front.next;
            return temp;
}
}
public void display()
{
if(front==null)
{
System.out.println("Queue is Empty");
}
else
{
System.out.println("Elements in the Queue");
Node current = front;
while(current != null)
{
System.out.println("[" + current.item + "] ");
current = current.next;
}
System.out.println("");
}
}

}



class QueueLinkedList
{
public static void main(String[] args) throws IOException
{
LinkedList ll = new LinkedList();
System.out.println("1INSERT\n2.DELETE\n3.DISPLAY");
while(true)
{
System.out.println("Enter the Key of the Operation");
int c=Integer.parseInt((new BufferedReader(new InputStreamReader(System.in))).readLine());
switch(c)
{
case 1:
System.out.println("Enter the Element");
int val=Integer.parseInt((new BufferedReader(new InputStreamReader(System.in))).readLine());
ll.insert(val);
break;
case 2:
int temp=ll.delete();
if(temp!=0)
System.out.println("Element deleted is [" + temp + "] ");
break;
case 3:
ll.display();
break;
case 4:
System.exit(0);
default:
System.out.println("You have entered invalid Key.\n Try again");
}
}
}
}

No comments:

Post a Comment

Best geography books for UPSC prelims, mains

This post is intended to clear the confusion that prevails among the aspirants over how to prepare for UPSC geography and the best books f...