5.5Priority Queue
With a linked list: inserting by priority
You can also build a priority queue from nodes. This time the list is sorted from small to large: the highest-priority element, the smallest value, is at the head of the list, in the node head points to. A new node is linked in at the right place for its priority and no element moves.
- Why the list is kept sorted from small to large and when the new node goes to the head
- How to find the right place with the
prevpointer and keep equal priorities in order - Why insertion takes O(n) and how it differs from the array version
1Idea
The structure has a single field: head. In an empty queue head is NULL. The list is sorted from small to large, so the highest-priority element is always at the head and removal happens at the head. In the array version the order was reversed, large to small. The cheap end of an array is its end; the cheap end of a linked list is its head.
First the new node is created. In C, if malloc returns NULL there is no memory and the function returns false. A linked list has no full queue; memory is the only limit.
The new node goes to the head in two cases: the list is empty, or the new value is smaller than the value at the head. Then the new node points to the old head and head moves to the new node. This is the same as inserting at the head.
Otherwise prev starts at the head. It moves forward as long as the next node's value is smaller than or equal to the new value. When it stops, the new node goes between prev and prev->next: first node->next = prev->next, then prev->next = node. This is the order from the inserting at a position lesson.
The head condition uses < and the walking condition uses <=. Both do the same job: the new element goes behind elements with an equal value. So with equal priorities the one that arrived first leaves first.
2Step by step
The drawing inserts 5 into a queue holding 2, 4, 7 and 9. The head is on the left; the highest-priority element, 2, is there. The new node is first created below the list, then linked into place.
- Start. head points to 2. The value to insert is 5.
- The new node is created and its value is 5. It is not linked to the list yet.
- The list is not empty and 5 is not smaller than 2 at the head: the new node does not go to the head.
prevstarts at the head, at 2. - The next node is 4. 4 is smaller than 5, so it must leave first.
prevmoves to 4. - The next node is 7. 7 is larger than 5. The loop stops; the new node will go between 4 and 7.
node->next = prev->next: the new node points to 7. The list has not changed yet.prev->next = node: 4 now points to 5. The new node is linked into the list.- Result: 2, 4, 5, 7, 9. The list is still sorted from small to large and no node moved.
struct Node { int data; struct Node* next;}; struct PQ { struct Node* head; // sorted from small to large}; bool insert(struct PQ* pq, int value) { struct Node* node = malloc(sizeof(struct Node)); if (node == NULL) return false; // out of memory node->data = value; if (pq->head == NULL || value < pq->head->data) { // goes to the head node->next = pq->head; pq->head = node; return true; } struct Node* prev = pq->head; while (prev->next != NULL && prev->next->data <= value) // behind its equals prev = prev->next; node->next = prev->next; prev->next = node; return true;}class Node { int data; Node next; Node(int data) { this.data = data; }} class LinkedPriorityQueue { Node head = null; // sorted from small to large void insert(int value) { Node node = new Node(value); if (head == null || value < head.data) { // goes to the head node.next = head; head = node; return; } Node prev = head; while (prev.next != null && prev.next.data <= value) // behind its equals prev = prev.next; node.next = prev.next; prev.next = node; }}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 insert(self, value): node = Node(value) if self.head is None or value < self.head.data: # goes to the head node.next = self.head self.head = node return prev = self.head while prev.next is not None and prev.next.data <= value: # behind its equals prev = prev.next node.next = prev.next prev.next = nodeThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
prev moves once for each element smaller than or equal to the new value. In the worst case the new value is the largest and the walk goes to the end of the list.
Apart from the new node, only one helper pointer is used.
If the new element has the highest priority it goes straight to the head and insertion takes O(1). In an array elements shift to open a slot; here only two pointers change (inserting with an array).
4Common mistake
A common mistake is to look at prev itself while walking, not at the next node:
struct Node* prev = pq->head;while (prev != NULL && prev->data <= value) prev = prev->next;node->next = prev->next; // prev may be NULLWhen this loop stops, prev is the first node larger than the new value, or NULL. The new node has to go in front of that node, but a singly linked list cannot step back. At the end of the list prev->next also reads through a NULL pointer. The right way is to look at the value of prev->next; then prev always stops at the node just before the new one.
5Try it
The list is 3, 6, 8. What happens when insert(1) is called?
The answer is A. 1 is smaller than 3 at the head, so the first condition holds. The new node points to the old head and head moves to the new node. There is no walk at all.
Show the answer
The answer is A. 1 is smaller than 3 at the head, so the first condition holds. The new node points to the old head and head moves to the new node. There is no walk at all.
The list is 2, 5, 9. Where does the new 5 go when insert(5) is called?
The answer is B. The walking condition is <=, so prev moves up to the old 5 and stops when the next node is 9. The new 5 comes after the old 5; with equal priorities the one that arrived first leaves first.
Show the answer
The answer is B. The walking condition is <=, so prev moves up to the old 5 and stops when the next node is 9. The new 5 comes after the old 5; with equal priorities the one that arrived first leaves first.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.