DEV Community

Jarvish John
Jarvish John

Posted on

CA 22 - Reverse a Linked List

Problem Statement

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

Examples:

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

My Goal

For this problem, my goal was to:

Understand how linked list pointers work
Reverse connections between nodes
Do it efficiently without extra space
Strengthen pointer manipulation skills

Solution

I used an iterative approach with three pointers.

Idea:

Use three pointers:
p → previous node
c → current node
n → next node
Reverse the link of current node
Move all pointers forward
Continue until list ends

Solution Code (Python)

class ListNode:
    def __init__(s, v=0, n=None):
        s.val = v
        s.next = n

def reverseList(h):
    p = None
    c = h

    while c:
        n = c.next
        c.next = p
        p = c
        c = n

    return p
Enter fullscreen mode Exit fullscreen mode

Explanation

Initially, p = None (new end of list)
Traverse through list using c
Reverse pointer: c.next = p
Move pointers forward
At the end, p becomes new head

Top comments (0)