Linked List Implementation of Queue
In this article, we discuss and implement the Linked List version of the Queue data structure. If the queue is empty, print -1.
Approach
To solve this problem, we maintain two pointers:
- Front: Points to the first item of the queue.
- Rear: Points to the last item of the queue.
Operations:
- enQueue(): Adds a new node after the rear and moves the rear to the next node.
- deQueue(): Removes the front node and moves the front to the next node.
Steps to Implement:
-
Create a class
QNodewith the following:- Data members:
int dataandQNode* next. - A parameterized constructor that takes an integer
xas a parameter, setsdata = x, and initializesnext = NULL.
- Data members:
-
Create a class
Queuewith data members:QNode* frontQNode* rear
-
Enqueue Operation (
enqueue(x)):- Initialize
QNode* tempwithdata = x. - If
rear == NULL:- Set
front = tempandrear = temp(Base Case). - Return.
- Set
- Else:
- Set
rear->next = temp. - Move
reartotemp.
- Set
- Initialize
-
Dequeue Operation (
dequeue()):- If
front == NULL, return (Base Case). - Initialize
QNode* temp = frontand movefronttofront->next. - If
front == NULL, setrear = NULL. - Delete
tempfrom memory.
- If