Linked lists · Exercise 19 of 100
Reverse a linked list
To reverse a list that ends, start at the head with an empty reversed part. At each node, save its next link so you can keep walking, then point the node back to the head of the reversed part. This node becomes the new head of that part.
Try it yourself
Starting at the head of the list 6, 1, 7, 3, process two nodes using this reversal method. Which value is at the head of the reversed part now?
One-step hint
Keep a separate row for the reversed part. Each time you process a node, put it at the front of that row.
Worked solution
- Save the link to 1 and clear the next link of 6, making 6 the only node in the reversed part.
- At 1, save the link to 7 and point 1 back to 6. The reversed part now starts at 1.