This is a common interview question asked and i usually confuse this a lot. :) As such any dummy i believe, if they think fast, you can never come with a correct solution.
Always reversing the list should be done for a single node first and then you should move the pointer.
Consider the below linked list. How would you reverse it with just single iteration.
The important things to consider here are, you need to change the head pointer to the last node in the list. The first node’s next should point to NULL. How would you do that?
If you use extra space, you create a new linked list and you remove the first node and append into the new list.
Similar to this way, we need to have a new “result” List pointing to NULL. The iterator we create “current” is pointing to head. At the first run, we do the following,
- Store the current->next
- change current->next to result (result will hold the last found head of the reversed list)
- set result to the current node(the first node is the last found head as of now)
- move current to the next node.
current = head
result = NULL
next = current->next
current->next = result
current = next
Do the above same thing again until current is not NULL. Finally we also handle setting the result to the current which is the last node.
The tricky thing here is, we just need 2 extra copy pointers. next and result. next holds the next node. result always holds the latest head node found.