algoritmauzmanı
Sign in
TREN
5.5Priority Queue
Lesson 5.5.5

With a linked list: removing the highest priority

The list is sorted from small to large, so the highest-priority element of the is always at the head. Removal is the same as deleting from the head: the value of the head node is taken, moves to the next node and in C the old node's memory is given back.

What you will learn
  • How removal from an empty queue is prevented
  • Why the head node is kept in a temporary pointer and when is called
  • Why removeMin and take
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

isEmpty returns true when head is NULL. Removing an element from an empty queue is an . In C removeMin returns false; Java throws IllegalStateException and Python raises IndexError. The message is "queue is empty".

If the queue is not empty there are four steps. Keep the address of the head node in temp. Write its value into *value. Move head to temp->next. Finally give temp back with . Java and Python have no free; the garbage collector reclaims the old node.

If the queue has a single node, temp->next is NULL. head becomes NULL and the queue is empty. No separate code is needed for this.

makes the same check, then reads head->data and leaves the list alone.

In an ordinary linked queue, dequeue also removes the head node. The real difference is in insertion: there the new node always goes to the end, here it goes to its place by priority. The removal code is nearly the same in both.

2Step by step

The drawing removes from a queue holding 2, 4, 5 and 7. The highest-priority element, 2, is in the head node.

NULL2?0x2c104?0x1a905?0x1b207?0x1a40headtemp
  1. Start. points to 2. This is the element that leaves.
  2. The queue is not empty. The address of the head node is saved in temp; once head changes, temp is the only way to reach that node.
  3. The node's value, 2, is read so it can be handed to the caller.
  4. head moves to the next node, 4. 2 is no longer part of the queue, but temp still points to it.
  5. In C the memory of 2 is returned with . Java and Python have no such line.
  6. Result: 4, 5, 7. The next highest-priority element is 4, again at the head. The function hands back 2; in C it returns true.

struct Node {    int data;    struct Node* next;}; struct PQ {    struct Node* head;  // sorted from small to large}; bool isEmpty(struct PQ* pq) {    return pq->head == NULL;} bool removeMin(struct PQ* pq, int* value) {    if (isEmpty(pq)) return false;  // the queue is empty    struct Node* temp = pq->head;  // the smallest value is at the head    *value = temp->data;    pq->head = temp->next;    free(temp);    return true;} bool peek(struct PQ* pq, int* value) {    if (isEmpty(pq)) return false;    *value = pq->head->data;    return true;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class LinkedPriorityQueue {    Node head = null;   // sorted from small to large     boolean isEmpty() {        return head == null;    }     int removeMin() {        if (isEmpty()) throw new IllegalStateException("queue is empty");        int value = head.data;  // the smallest value is at the head        head = head.next;        return value;    }     int peek() {        if (isEmpty()) throw new IllegalStateException("queue is empty");        return head.data;    }}
class Node:    def __init__(self, data):        self.data = data        self.next = None class LinkedPriorityQueue:    def __init__(self):        self.head = None  # sorted from small to large     def is_empty(self):        return self.head is None     def remove_min(self):        if self.is_empty():            raise IndexError("queue is empty")        value = self.head.data  # the smallest value is at the head        self.head = self.head.next        return value     def peek(self):        if self.is_empty():            raise IndexError("queue is empty")        return self.head.data

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

3Complexity

Time
O(1)

Independent of the number of elements: one comparison, a few assignments and one free.

Memory
O(1)

Only one helper pointer is used.

The price of this speed is paid at insertion: finding the new node's place makes insertion . In the array version removal is O(1) as well (removing with an array).

4Common mistake

The most common mistake is reading a node's fields after freeing it:

free(pq->head);*value = pq->head->data;   // freed memorypq->head = pq->head->next;

After free, pq->head is a . The code sometimes seems to work, sometimes reads a wrong value or crashes. The right order: save it in temp, read the value, move head, call free last. Leaving out free is a mistake too: every removal leaves one node's worth of .

5Try it

The list is 1, 3, 3, 8. If removeMin() is called three times, what does the last call return?

Show the answer

The answer is A. The calls return 1, then the 3 inserted first, then the 3 inserted later. The list is sorted, so every removal takes the smallest value at the head. Only 8 is left in the queue.

What happens to head when removeMin() is called on a queue with a single node?

Show the answer

The answer is A. The single node's next field is NULL. The line head = temp->next sets head to NULL; isEmpty now returns true.

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