algoritmauzmanı
Sign in
TREN
5.3Queue with a Linked List
Lesson 5.3.2

Enqueue: adding a node at the rear

adds a new element at the back of the queue. In a queue built on a linked list this is the fast version of inserting at the end: instead of walking the list, the pointer already points to the last node. In this lesson you see the steps and why the empty queue is handled on its own.

What you will learn
  • How the new node is prepared and why its next is NULL
  • In what order the node is linked after rear
  • Why front changes too when the queue is empty
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

First a new is allocated, its value is written and its next is set to : this node goes to the back of the queue, and nobody will stand behind it. In C, if returns NULL there is no memory left; the function returns false and the queue is unchanged.

If the queue is not empty, two assignments are enough. First the last node's next is linked to the new node: rear->next = node. Then rear moves to the new node. The order matters: if you move rear first, you lose the old last node and cannot link it to the new one.

If the queue is empty, rear is and there is no rear->next field. In this case the new node is both the first and the last element: front and rear both point to it. If this branch is forgotten, front stays NULL and the queue keeps looking empty.

2Step by step

The drawing adds 30 to a queue holding 10 and 20. The front is on the left, the rear on the right. At each step the matching line of code lights up.

NULL10?0x1a4020?0x1a9030?0x2c10frontrearnode
  1. Start. front points to 10 and rear to 20.
  2. A new node is allocated. In C, if malloc returned NULL, the function would return false here.
  3. The value 30 is written and next is set to NULL. The node is not linked to the queue yet.
  4. rear is not NULL, so the queue is not empty. The else branch runs.
  5. rear->next = node: the last node, 20, now points to 30. The chain is 10, 20, 30.
  6. rear moves to the new node. The next enqueue will add after 30.
  7. Result: 10 at the front, 30 at the rear. front was not touched; the function returns true.

struct Node {    int data;    struct Node* next;}; struct Queue {    struct Node* front;    struct Node* rear;}; bool enqueue(struct Queue* q, int value) {    struct Node* node = malloc(sizeof(struct Node));    if (node == NULL) return false;  // out of memory    node->data = value;    node->next = NULL;    if (q->rear == NULL) {           // empty queue        q->front = node;        q->rear = node;    } else {        q->rear->next = node;        // link after the last node        q->rear = node;    }    return true;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class LinkedQueue {    Node front = null;    Node rear = null;     void enqueue(int value) {        Node node = new Node(value);        if (rear == null) {      // empty queue            front = node;            rear = node;        } else {            rear.next = node;    // link after the last node            rear = node;        }    }}
class Node:    def __init__(self, data):        self.data = data        self.next = None class LinkedQueue:    def __init__(self):        self.front = None        self.rear = None     def enqueue(self, value):        node = Node(value)        if self.rear is None:     # empty queue            self.front = node            self.rear = node        else:            self.rear.next = node  # link after the last node            self.rear = node

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(1)

The number of elements does not matter: one allocation and a few assignments.

Memory
O(1)

Each enqueue allocates one node; the operation itself uses no extra room.

Without rear, adding at the end would the list from the start and enqueue would be . The tail idea from inserting at the end is used here under the name rear.

4Common mistake

The most common mistake is forgetting the empty-queue branch:

q->rear->next = node;   // rear is NULL if emptyq->rear = node;

On an empty queue q->rear is NULL, and writing to q->rear->next crashes the program. In Java you get a NullPointerException. Another mistake is setting only rear on an empty queue and leaving front NULL: the queue holds an element, but isEmpty returns true and cannot remove anything.

5Try it

After enqueue(5) on an empty linked-list queue, what are front and rear?

Show the answer

The answer is B. A single element is both the first and the last to arrive. The empty-queue branch links both front and rear to the new node.

If the two lines in enqueue swap places on a non-empty queue (rear = node first, then rear->next = node), what happens?

Show the answer

The answer is B. Once rear has moved, rear->next = node writes into the new node itself. The old last node's next stays NULL, so the new element never shows up in the chain that starts at front.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.