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

Dequeue: removing the front node

removes the element at the front of the queue and returns its value. In a queue built on a linked list this is the same as deleting from the head: moves one node ahead. The only difference is that is set to NULL when the queue becomes empty. In this lesson you see why that line is needed.

What you will learn
  • In what order the front node is removed
  • Why rear is also set to NULL when the last node leaves
  • How dequeue behaves on an empty queue
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

First the code checks whether the queue is empty. If front is NULL there is nothing to remove: the C code returns false, while Java and Python throw an error. This case is the same as in a stack.

If the queue is not empty, the front node is kept in a temporary pointer, its value is read and front moves to the next node. In C the old node is released at the end with . In Java and Python nothing points to the node any more, and the garbage collector cleans it up.

One line belongs to the queue alone. If the node that leaves is the last one, front becomes NULL but rear still points to that node. In C that node is about to be freed, so rear becomes a . That is why rear is set to NULL once front is NULL, and the queue really returns to its empty starting state.

2Step by step

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

NULL10?0x1a4020?0x1a9030?0x2c10frontreartemp
  1. Start. front points to 10 and rear to 30.
  2. The queue is not empty. The front node is kept in temp; soon front will leave it.
  3. The value is read: 10 will be returned.
  4. front moves to the next node. The front of the queue is now 20.
  5. front is not NULL, so the queue still holds elements. rear is not touched.
  6. In C the old node is released with free. In Java and Python the garbage collector does this.
  7. Result: 20 and 30 remain in the queue. The function returns 10.

struct Node {    int data;    struct Node* next;}; struct Queue {    struct Node* front;    struct Node* rear;}; bool dequeue(struct Queue* q, int* value) {    if (q->front == NULL) return false;  // empty queue    struct Node* temp = q->front;    *value = temp->data;    q->front = temp->next;    if (q->front == NULL)    // last node left        q->rear = NULL;    free(temp);    return true;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class LinkedQueue {    Node front = null;    Node rear = null;     int dequeue() {        if (front == null)            throw new IllegalStateException("queue is empty");        int value = front.data;        front = front.next;        if (front == null)       // last node left            rear = null;        return value;    }}
class Node:    def __init__(self, data):        self.data = data        self.next = None class LinkedQueue:    def __init__(self):        self.front = None        self.rear = None     def dequeue(self):        if self.front is None:            raise IndexError("queue is empty")        value = self.front.data        self.front = self.front.next        if self.front is None:    # last node left            self.rear = None        return value

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: only the front node is touched.

Memory
O(1)

No extra room is needed; in fact one node of memory is given back.

The queue removes from the head of the linked list and adds at the end. With the opposite choice, removing from the end would need the node before the last one, and dequeue would be . The lesson on creating the queue explains this choice.

4Common mistake

The most common mistake is forgetting rear when the last node leaves:

q->front = temp->next;   // front became NULLfree(temp);              // rear still points here

The queue is empty, but rear points to a freed node. The next does not see rear as NULL, writes to rear->next and corrupts memory that is no longer yours. Since front also stayed NULL, the new element does not show up in the queue. In Java and Python the program does not crash, but the same error happens: the new element is linked after the old, detached node and is lost.

5Try it

The queue holds only 7. After dequeue, what are front and rear?

Show the answer

The answer is B. When the last node leaves, front becomes NULL and the code sets rear to NULL too. With both NULL, the queue is in its empty starting state.

Why is free(temp) near the end of the C code?

Show the answer

The answer is A. Using a node's fields after free is undefined behaviour. The value is read, front moves to temp->next, and only then is the node released.

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