DEV Community

Cover image for LeetCode 206: Reverse Linked List - (Easy)
Grant Riordan
Grant Riordan

Posted on

LeetCode 206: Reverse Linked List - (Easy)

Given the head of a singly linked list, reverse the list, and return the reversed list.

example of reversal

Approach & Solution

We reverse a linked list by keeping track of two pointers: prev (the previous node) and curr (the current node). At each step, we:

  • Save the next node so we don’t lose track of the list.

  • Reverse the current node’s pointer to point to prev.

  • Move prev forward to curr.

  • Move curr forward to the saved next node.

We continue until curr is null, meaning we’ve processed all nodes. At that point, prev will be the new head of the reversed list.

Code

ListNode ReverseList(ListNode head)
{
ListNode prev = null;
ListNode curr = head;

while (curr != null)
{
    ListNode nextNode = curr.next;
    curr.next = prev;
    prev = curr;
    curr = nextNode;
}

return prev; // new head
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)