Write a function that dequeues a node from a singly linked list. Printing the de
ID: 3854342 • Letter: W
Question
Write a function that dequeues a node from a singly linked list. Printing the dequeued value and returning the modified head.
node* Queue::dequeue()
The function is a member of a class called Queue. Write the function definition only for dequeue. Given below is the class definition:
struct node
{
int value;
node *next;
};
class Queue
{
public:
Queue(node *, node *);
virtual ~Queue();
node* dequeue();
void displayQueue();
protected:
private:
node *head;
node *tail;
};
For example:
Test Result //75 -> 100 -> 125 -> 150 75100 -> 125 -> 150 -> nullptr
Explanation / Answer
The function code for dequeue() is as follows:
node* dequeue()
{
'struct node tmp; //This temporary node will be used to store and display the dequeued member
tmp=head; //Storing the pointer of the first node in Queue in tmp variable
if(tmp==NULL) /*This means that head variable was NULL, which can only happen if there are no elements in Queue*/
printf("Queue is empty");
else
{
head=head->next; /*Accessing the next element in the Queue whose address is stored in head->next variable and updating the value of head now as the previously 2nd element on the Queue*/
printf("The element dequeued is %d", tmp->value); /*tmp still contains the original head address, that is, the adress of element removed, so we print its value*/
}
return tmp; /*We finally return the address of removed node*/
}
Hope these comments help to understand the code, step by step.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.