Lecture 3
Linked List quiz
Answer each question to see whether you got it right and why. Your answers are saved in this browser.
What is a linked list?
Each node holds data and a pointer to the next node. The nodes are allocated separately on the heap, not in one block.
In a singly linked list, the last node's
nextpointer isnullptr.A
nullptrinnextis how you recognize the end of the list.Given the declarations below, which expression reads the
countof the node thatppoints to?struct elType { std::string word; int count; }; struct node { elType e; node* next; }; node* p = new node;pis a pointer, so->follows it to the node.eis a plain struct member, so.countfinishes the access.After
p = new node;,p->nextis automaticallynullptr.new nodeleavesnextuninitialized, so it holds garbage until you assign it. Always setnextright away.What is the main advantage of a linked list over an array?
Only a few pointers change. The cost is that reaching a position means walking from
head, and each node carries an extra pointer.Which pair of statements correctly inserts node
pat the head of the list, in the right order?Link the new node to the old first node first, then move
head. Doing it the other way overwritesheadand the new node points at itself.What goes wrong in this insert-at-head code?
head = p; p->next = head;head = p;runs first, sop->next = head;copiespintop->next. The old nodes are no longer reachable (leaked).To insert
paftercursor, the first statement must be:pmust first take over the rest of the list (cursor->next). If you redirectcursor->nextfirst, you lose the successor.Inserting at the head works on an empty list without any special case.
headisnullptr, sop->next = head;gives the new node anullptrnext, andhead = p;makes it the only node.Run this code on
head -> 3 -> 5. Type the keys of the final list in order, separated by spaces.Node* a = new Node{1, head}; head = a; Node* b = new Node{9, a->next}; a->next = b;After the first two lines the list is 1 -> 3 -> 5. Then 9 is inserted after the node holding 1, giving 1 -> 9 -> 3 -> 5.
Which sequence deletes the head node safely?
Save the node, move
headforward, then delete the saved node. Deleting first and then readinghead->nextis use-after-free.delete head; head = head->next;is a safe way to remove the first node.After
delete head;the node no longer exists, so readinghead->nextis undefined behaviour.Why does deleting a non-head node in a singly linked list need its predecessor?
The only pointer that refers to the node lives in its predecessor, so that is the pointer you must change.
In
4 -> 8 -> 12 -> 16,cursorpoints at 8. After this code runs, type the keys of the list in order, separated by spaces.Node* q = cursor->next; cursor->next = q->next; delete q;qis the node after the cursor (12).cursor->next = q->nextlinks 8 to 16, and 12 is freed.A node created with
new nodeshould be freed withdelete[].delete[]is only for arrays fromnew[]. A single node uses plaindelete.In a circular singly linked list,
tail->next == head.The last node points back to the first, so there is no
nullptrat the end.Why does
while (p != nullptr) { ...; p = p->next; }never finish on a circular list?In a circular list every node has a real successor. Stop when
preturns toheadinstead.In a doubly linked list, which statement moves the cursor to the previous node (slides notation)?
Each node has
nextandbackpointers.backpoints at the predecessor.Why is the
nodeclass declared in the private part ofList?Hiding the representation is the ADT idea: callers depend only on the operations.
What is the purpose of the
prevpointer in theListclass?In a singly linked list a node can't find its predecessor, so
Listkeeps it alongsidecursor.toFirst()on an empty list leaves the current position empty.cursor = headcopiesnullptr, so there is still no current node.When
search(k)does not find the key, what happens?On success the cursor sits on the match and the function returns
true. On failure it returnsfalseand the current position is empty.After
deleteEnd(), what is the current position?deleteEnddeletes the last node and sets the current position to empty.Where does this loop leave
cursor?toFirst(); if (!listIsEmpty()) while (cursor->next != NULL) advance();The loop stops when
cursor->next == NULL, which is true on the last node. Stopping oncursor == NULLwould walk past it.What does
listSize()return for the list7 -> 2 -> 9?NodePointer q = head; int count = 0; while (q != NULL) { count++; q = q->next; } return count;The loop visits three nodes, incrementing
counteach time, beforeqbecomesNULL.What happens if
~List()is empty?Nodes are allocated with
newand are never freed automatically, so the destructor must callmakeListEmpty().After
insertFirst(k, d), which node is current?The code sets
cursor = head(the new node) andprev = NULL.According to the lecture slides,
insertAfterleaves the current position unchanged.The slides define
insertAfteras inserting after the current node "without changing the current position". The practice sheet question 14 uses its own rule, so follow the rules a question states.A function must insert at the head and change the caller's
head. Which parameter does it need?head = pinside the function must change the caller's pointer, so the parameter has to be a reference to a pointer (Lecture 1 and 2).Start with
head -> A(4) -> B(8) -> C(12),tailat C. Insert D(6) after A, delete B, insert E(2) at the head, then append F(14). Type the node names in order, separated by spaces. (Practice sheet Q11)A -> D -> B -> C, then A -> D -> C, then E -> A -> D -> C, then E -> A -> D -> C -> F.
Appending F after C when the list tracks
headandtail: which assignments are needed? (Practice sheet Q11)F becomes the last node (
nullptrnext), the old last node links to it, andtailmust move. Forgettingtail = Fleavestailon C.The list is
A -> D -> B -> C. Which single assignment unlinks B (before freeing it)? (Practice sheet Q11)D is B's predecessor, so D's
nextmust skip B and point at C.A list holds
7 -> 3 -> 7. Using thisremoveFirst, after the first callremoveFirst(7), type the keys of the list in order, separated by spaces. (Practice sheet Q12)bool removeFirst(int key) { Node* prev = nullptr; Node* node = head; while (node && node->key != key) { prev = node; node = node->next; } if (!node) return false; if (prev) prev->next = node->next; else head = node->next; if (node == tail) tail = prev; delete node; return true; }The first 7 is the head.
previsnullptr, sohead = node->next. The list becomes 3 -> 7.After the second call
removeFirst(7)on3 -> 7, what key doestailpoint at? (Practice sheet Q12)The removed node was the tail (
node == tail), sotail = prev, which is the node holding 3.After
removeFirst(3)on the one-node list3, what areheadandtail? (Practice sheet Q12)previsnullptr, sohead = node->next = nullptr. Sincenode == tail,tail = prev = nullptras well.In
removeFirst, why isif (node == tail) tail = prev;needed? (Practice sheet Q12)If the deleted node was the last one,
tailwould point at freed memory.previs the new last node (ornullptrif the list became empty).In this
orderedInsert, the loop condition isnext && next->key <= key. What does<=guarantee? (Practice sheet Q13)void orderedInsert(int key) { Node* prev = nullptr; Node* next = head; while (next && next->key <= key) { prev = next; next = next->next; } Node* node = new Node{key, next}; if (prev) prev->next = node; else head = node; if (!next) tail = node; }<=keeps walking past equal keys, so a new duplicate lands after the existing ones and equal keys keep their insertion order.In
4 -> 9a -> 9b -> 15, where does the new node9cgo? (Practice sheet Q13)The loop passes both existing 9s (
<=) and stops at 15, so 9c is inserted right before 15.Start with
4 -> 9a -> 9b -> 15. Insert 2, then 9c, then 20. Type the final list in order, separated by spaces. (Practice sheet Q13)2 becomes the new head, 9c goes after 9b, and 20 becomes the new tail.
In
orderedInsert,tailmust be updated when the loop ends withnext == nullptr. (Practice sheet Q13)next == nullptrmeans the new node was inserted after the last node, so it is the new tail.The list is
10 -> 20 -> 30,currentis at 20. Using the sheet's rules, afterinsertAfter(25)which key doescurrenthold? (Practice sheet Q14)The sheet states that insertion moves current to the new node, so
currentis 25 and the list is 10 -> 20 -> 25 -> 30.Continuing:
currentis at 25 in10 -> 20 -> 25 -> 30. Afteradvance(), which key doescurrenthold? (Practice sheet Q14)advance()movescurrentone node forward, from 25 to 30.Continuing:
currentis at 30. AfterdeleteEnd(), what key doestailhold? (currentis cleared.) (Practice sheet Q14)30 is removed, so the last node is 25 and
tailmoves there. The list is 10 -> 20 -> 25 andcurrentisnullptr.List
10 -> 20 -> 25,currentis at 25 (aftertoEnd()).deleteHead()clearscurrent. (Practice sheet Q14)The sheet's rule:
deleteHead()clearscurrentonly if it selected the deleted node. Herecurrentis 25, not 10, so it stays at 25 and the list becomes 20 -> 25.Circular doubly list
A <-> B <-> C <-> D,head = A. Which assignments remove A and make B the head? (Practice sheet Q15)D's
nextand B'sprevmust bypass A, andheadmoves to B. Then A can be freed.How many link assignments does inserting X between D and B require? (Practice sheet Q15)
X->prev = D; X->next = B; D->next = X; B->prev = X;are four assignments: two on the new node and one on each neighbour.After inserting X between D and B (
head = B), type the first five nodes visited going forward fromhead, separated by spaces. (Practice sheet Q15)Following
next: B -> C -> D -> X -> B. It returns to B because the list is circular.Same list: type the first five nodes visited going backward (
prev) fromhead, separated by spaces. (Practice sheet Q15)Following
prev: B -> X -> D -> C -> B.