Skip to content

Instantly share code, notes, and snippets.

@anil477
Created May 28, 2017 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/b45fd3a947ab77d3537b7b90812f293b to your computer and use it in GitHub Desktop.
Save anil477/b45fd3a947ab77d3537b7b90812f293b to your computer and use it in GitHub Desktop.
Queue Using Linked List
// A linked list (LL) node to store a queue entry
class QNode
{
public int key;
public QNode next;
// constructor to create a new linked list node
public QNode(int key) {
this.key = key;
this.next = null;
}
}
// A class to represent a queue
//The queue, front stores the front node of LL and rear stores ths
//last node of LL
class Queue
{
QNode front, rear;
public Queue() {
front = rear = null;
}
// Method to add an key to the queue.
void enqueue(int n)
{
// Create a new LL node
QNode temp = new QNode(n);
// If queue is empty, then new node is front and rear both
if (rear == null)
{
front = rear = temp;
System.out.println("Queued: " + temp.key);
return;
}
// Add the new node at the end of queue and change rear
rear.next = temp;
rear = temp;
System.out.println("Queued: " + temp.key);
}
// Method to remove an key from queue.
QNode dequeue()
{
// If queue is empty, return NULL.
if (front == null){
System.out.println("Empty Queue");
return null;
}
// Store previous front and move front one node ahead
QNode temp = front;
System.out.println("Deqeued: " + temp.key);
front = front.next;
// If front becomes NULL, then change rear also as NULL
if (front == null)
rear = null;
return temp;
}
}
class Test
{
public static void main(String[] args)
{
Queue q = new Queue();
q.enqueue(10);
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
q.dequeue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment