Linked lists · Exercise 16 of 100
Build a singly linked list
A singly linked list has a head that points to the first node, and each node links to the next. To insert a node after an existing one, first link the new node to the old successor, then link the existing node to the new one. Doing this in order keeps the rest of the list connected.
Try it yourself
A list starts with 4 followed by 9. Insert 7 immediately after 4, then add 2 as the new head. What is the third value when counting from the head, starting at 1?
One-step hint
Draw boxes for the original pair, splice the inserted box between them, then number the boxes starting at the new head.
Worked solution
- Link 7 to 9, then link 4 to 7. The order is now 4, 7, 9.
- Link the new head 2 to 4. Counting along 2, 4, 7, 9 puts 7 in third place.