Linked Lists: the queue.

The new node is now the last node in the queue, so we update the rear pointer to point to the actual end of the queue.void enqueue(int v_) { node* temp = new node(v_); if(!front) //case 1: the queue is empty..front = rear = temp; else { //case 2: the queue has nodes..Now update the front pointer to the node that links to the front, or in other words point front to the second to front node.void dequeue() { if(!front) { //case 1: the queue is empty, do nothing..node* t = front; front = rear = NULL; delete t; } else { //case 3: the queue has more than one node..node* t = front; node* s = rear; //walk the links to the 2nd to front node while( s->link != front ) s = s->link; front = s; //update the front of the queue s->link = NULL; delete t; }}Now put it all together to make the linked list queue.class Queue { private: struct node { node* link; int value; node(int v_) : value(v_), link(NULL) {}; }; node* front; node* rear; public: void enqueue(int v_) { node* temp = new node(v_); if(!front) //case 1: the queue is empty..node* t = front; node* s = rear; //crawls the links while( s->link != front ) s = s->link; front = s; //update the front of the queue s->link = NULL; delete t; } } Queue() { front = NULL; rear = NULL; }};And there is a linked list queue that enqueues and dequeues nodes.Copy the full source code here into a text editor and save as main.cppCompile from command line, g++ main.cpp -std=c++11 -o Queue.exeThen execute the code from command line, ./Queue.exeAfter compiling and executing, the program will generate a queue, enqueuing and dequeuing nodes.. More details

Leave a Reply