In C++ A queue is a data structure where items can only be added to the end (enq
ID: 3734250 • Letter: I
Question
In C++
A queue is a data structure where items can only be added to the end (enqueue) and items can only be removed from the front (dequeue).
A queue can easily be implemented as a linked list.
Create a node structure that contains an integer variable and a pointer to the next node
Write an EnQueue function
The parameters will be an integer value to add to the list and a Node pointer that points to the head of the list
Write a DeQueuefunction
It will only have a Node pointer parameter (the head of the list)
Write a driver program to test the functions.
Create a recursive print function so that you can see if the EnQueue and DeQueue functions are working properly.
Explanation / Answer
Please fin my implementation.
// A C program to demonstrate linked list based implementation of queue
#include <stdlib.h>
#include <stdio.h>
// A linked list (LL) node to store a queue entry
struct QNode
{
int key;
struct QNode *next;
}*head = NULL;
// The function to add a key k to q
void enQueue(int k)
{
// Create a new LL node
QNode *temp = new QNode;
temp->next = NULL;
temp->key = k;
if(head == NULL) {
head = temp;
}else{
QNode *t = head;
while(t->next != NULL)
t = t->next;
t->next = temp;
}
}
// Function to remove a key from given queue q
void deQueue()
{
// If queue is empty, return NULL.
if (head == NULL)
return;
// Store previous head and move head one node ahead
QNode *temp = head;
head = head->next;
delete temp;
}
// Driver Program to test anove functions
int main()
{
enQueue( 10);
enQueue( 20);
deQueue();
deQueue();
enQueue( 30);
enQueue( 40);
enQueue( 50);
deQueue();
return 0;
}