Implement Queue using Linked List - The Coding Shala

Home >> Data Structure >> Implement queue using linked list

 In this post, we will learn how to implement Queue using Linked List and will write a Java Program for the same.

Implement Queue using Linked List

We will implement Queue using Linked List. The basic operation of the queue like push/offer and remove/poll method will implement here.

Java Program: 

class QueueNode
{
	int data;
	QueueNode next;
	QueueNode(int a)
	{
	    data = a;
	    next = null;
	}
}

class MyQueue
{
    QueueNode front, rear;
    
    // This function should add an item at
    // rear
	void push(int a)
	{
	    QueueNode newNode = new QueueNode(a);
	    if(front == null || rear == null) {
	        front = newNode;
	        rear = front;
	    } else {
        rear.next = newNode;
        rear = rear.next;
	    }
	}
	
    // This function should remove front
    // item from queue and should return
    // the removed item.
	int pop()
	{
	    if(front == null) return -1;
        int res = front.data;
        front = front.next;
        return res;
	}
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Time Complexity, Space Complexity, Asymptotic Notations - The Coding Shala

Sort an Array According to Count of 1(set) bits - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala