DEV Community

VARUN
VARUN

Posted on

CA 22 - Reverse a Linked List

1.Problem Understanding

Reverse the given entire singly linked list.

Example:
Input: 1 → 2 → 3 → 4 → 5
Output: 5 → 4 → 3 → 2 → 1

2.Idea
You need 3 pointers:
prev → previous node
curr → current node
next → next node

store next
reverse current pointer
move forward
3.Example:
Start:
NULL ← 1 → 2 → 3 → 4 → 5
Step 1:
NULL ← 1 2 → 3 → 4 → 5
Step 2:
NULL ← 1 ← 2 3 → 4 → 5
Step 3:
NULL ← 1 ← 2 ← 3 4 → 5
Final:
NULL ← 1 ← 2 ← 3 ← 4 ← 5
New head = last node (5)

4.Algorithm (Simple Steps)
Initialize:
prev = None
curr = head
Loop until curr == None:
store next node
reverse link
move pointers forward
Return prev (new head)

Top comments (0)