Queue
This article assumes that you have already read Linked-List in C and does not provide much explanation.
A queue is a linear data structure that follows the FIFO (First-In, First-Out) architecture. It is like how people stand in a queue to buy something. The first person who goes in is the first person who buys the product and comes out.
Structure
The structure is the same as a singly linked-list.
struct Node { int data; struct Node *next;};
However, the queue involves two pointers, the front
and the rear
.
struct Node *FRONT;struct Node *REAR;
New nodes are inserted at the rear and accessed from the front.
What We Have
#include <stdlib.h>struct Node { int data; struct Node *next;};struct Node *FRONT;struct Node *REAR;void enqueue(int item_to_insert) { struct Node *new_item = (struct Node *)malloc(sizeof(struct Node)); new_item->data = item_to_insert; new_item->next = NULL; if (REAR == NULL) { REAR = new_item; FRONT = new_item; } else { struct Node *temp = REAR; REAR = new_item; temp->next = REAR; }}void dequeue() { if (FRONT == NULL) return; // Return on empty queue else { struct Node *temp = FRONT; if(FRONT->next == NULL) { FRONT = NULL; REAR = NULL; } else { FRONT = FRONT->next; free(temp); } }}
See Also
Table of Contents