Queue

This article assumes that you have already read Linked-List in C and does not provide much explanation.

This article is a sligtly sane approach towards how a queue works, using only ONE pointer, the FRONT.

This article was written because of the author's own decision, and does not intend to portray this as the perfect example of a queue.

Structure

The structure is the same as a singly linked-list.

struct Node {    int data;    struct Node *next;};

And then the head of our queue,

struct Node *FRONT;

Code

#include <stdlib.h>struct Node {    int data;    struct Node *next;};struct Node *FRONT;// Following the `insert_at_end` algorithm for a singly linked-listvoid 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 (FRONT == NULL) {        FRONT = new_item;    } else {        struct Node *temp = FRONT;        while (temp->next != NULL) {            temp = temp->next;        }        temp->next = new_item;    }}void dequeue() {    if (FRONT == NULL)        return; // Return in case of empty queue    else {        struct Node *temp = FRONT;        FRONT = FRONT->next;        free(temp);    }}

See Also

Table of Contents