DEV Community

Navin S
Navin S

Posted on

๐Ÿ” Reverse a Linked List (Step-by-Step Guide)

Reversing a linked list is one of the most important and commonly asked problems in data structures.
It helps you understand pointer manipulation and traversal logic.


๐Ÿ“Œ Problem Statement

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


๐Ÿ” Example

Input:
1 โ†’ 2 โ†’ 3 โ†’ 4 โ†’ 5 โ†’ NULL

Output:
5 โ†’ 4 โ†’ 3 โ†’ 2 โ†’ 1 โ†’ NULL


๐Ÿง  Intuition

In a linked list, each node points to the next node.

๐Ÿ‘‰ To reverse it, we need to:

  • Change the direction of each pointer
  • Make each node point to the previous node instead

๐Ÿ”„ Approach (Iterative Method)

Step-by-Step:

  1. Initialize three pointers:
  • prev = None
  • current = head
  • next_node = None
  1. Traverse the list:
  • Store next node
  • Reverse current pointer
  • Move pointers forward

๐Ÿ’ป Python Code

```python id="rev1"
class ListNode:
def init(self, val=0, next=None):
self.val = val
self.next = next

def reverseList(head):
prev = None
current = head

while current:
    next_node = current.next   # store next
    current.next = prev        # reverse link
    prev = current             # move prev
    current = next_node        # move current

return prev
Enter fullscreen mode Exit fullscreen mode



---

๐Ÿงพ Dry Run

For: 1 โ†’ 2 โ†’ 3 โ†’ NULL

Step-by-step:

* Step 1: 1 โ†’ NULL
* Step 2: 2 โ†’ 1 โ†’ NULL
* Step 3: 3 โ†’ 2 โ†’ 1 โ†’ NULL

Final: 3 โ†’ 2 โ†’ 1 โ†’ NULL

---

โšก Complexity

Time Complexity: O(n)
Space Complexity: O(1)

---

๐Ÿ”ฅ Why This Works

* Each node is visited once
* Links are reversed in-place
* No extra memory required

---

๐Ÿ” Alternative Approach (Recursive)



```python id="rev2"
def reverseList(head):
    if not head or not head.next:
        return head

    new_head = reverseList(head.next)

    head.next.next = head
    head.next = None

    return new_head
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ Edge Cases

  • Empty list โ†’ return None
  • Single node โ†’ return same node

๐Ÿ Conclusion

Reversing a linked list is a core problem that teaches:

  • Pointer manipulation
  • Iterative vs recursive thinking
  • In-place operations

Top comments (0)