The idea is to always keep a reference to the previous-node and next-node. We will always be operating in the context of the current node.
In every iteration, the steps will be:
1. Get reference to next node.
2. Detach the link between current and next node.
3. Create a link between current and previous node.
4. Update Previous node – The new previous node will be the present current node.
5. Update reference to current node – The new current node will be the present next node.
All of the above performed in that order. The iteration ends when current node becomes null.
We use 3 references:
- prev – refers to the previous node.
- curr – refers to the current node.
- next – refers to the next node.
Here is an example:
prev = None
curr = start
while curr != None:
next = curr.link
curr.link = prev
prev = curr
curr = next
start = prev