Skip to content

Reversing a Linked List

Course: Linked List - chapter 3

Q - https://leetcode.com/problems/reverse-linked-list/description/

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:

  1. Maintain 2 pointers: curr and prev. curr is the current node we are at, and prev points to the previous node of curr in actual linked list
  2. Iterate till we reach the end
  3. 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
  4. Also, do maintain the actual curr→next separately 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;
}