Reversing a Linked List
Course: Linked List - chapter 3
Q - https://leetcode.com/problems/reverse-linked-list/description/
Solution
Section titled “Solution”Generally how we will approach linked list problems is, as we iterate try solving the problem till the current node. In this case, as we iterate, reverse the linked list for the nodes we have seen. What do we need? To reverse a node, we need the pointer to the previous node, because node→next = prev for a reversed linked list. Also, we should also maintain the pointer to the actual next node as once we set node->next = prev the actual next node will be impossible to reach, if we don’t maintain it manually.
Steps:
- Maintain 2 pointers:
currandprev.curris the current node we are at, andprevpoints to the previous node ofcurrin actual linked list - Iterate till we reach the end
- In each iteration, we will reverse the current node. To reverse a node, we will make it’s next point to the previous node. Or,
curr->next = prev - Also, do maintain the actual
curr→nextseparately before the assignment, otherwise we cannot proceed with the iteration.
ListNode* reverseList(ListNode* head) { ListNode* curr = head; ListNode* prev = NULL;
while(curr != NULL) { ListNode *next = curr->next; curr->next = prev; prev = curr; curr = next; }
return prev;}