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

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala