#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Linked Lists

Reverse Linked List

Reversing a linked list means changing the direction of the next pointers so that the last node becomes the head and the original head becomes the tail.

Iterative Approach

Traverse the list while keeping track of the previous, current, and next nodes, reversing the next pointer at each step.

def reverse_list(head):
    prev = None
    current = head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev  # new head

Recursive Approach

Recursively reverse the rest of the list, then fix the pointers on the way back up the call stack.

def reverse_list_recursive(head):
    if head is None or head.next is None:
        return head
    new_head = reverse_list_recursive(head.next)
    head.next.next = head
    head.next = None
    return new_head

Complexity

ApproachTimeSpace
IterativeO(n)O(1)
RecursiveO(n)O(n) (call stack)

Applications

  • Palindrome checking on linked lists.
  • Undo functionality where operations need to be replayed in reverse.
  • A common building block in problems like reversing sub-portions of a list or reversing in groups of k.

Tracing the Iterative Version Pointer by Pointer

Pointer problems become much easier once you trace them in a table. Here is the iterative algorithm running on the list 1 -> 2 -> 3 -> None:

Stepprevcurrentnext_nodeList state after step
StartNone1-1 -> 2 -> 3
1122None <- 1 , 2 -> 3
2233None <- 1 <- 2 , 3
33NoneNoneNone <- 1 <- 2 <- 3

The loop stops when current becomes None. At that moment prev points to node 3, which is the new head. The key idea is that next_node must be saved before the link is flipped, otherwise the rest of the list is lost.

Testing It with a Small Helper

Writing tiny helpers to build and print lists lets you test edge cases quickly instead of reasoning only in your head:

class ListNode:
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

def build(values):
    head = None
    for v in reversed(values):
        head = ListNode(v, head)
    return head

def to_list(head):
    out = []
    while head:
        out.append(head.val)
        head = head.next
    return out

print(to_list(reverse_list(build([1, 2, 3, 4]))))   # [4, 3, 2, 1]
print(to_list(reverse_list(build([7]))))            # [7]
print(to_list(reverse_list(build([]))))             # []

Always test an empty list, a single node and two nodes. Most pointer bugs show up in one of those three cases.

Variation: Reverse Only Part of the List

A frequent follow-up asks you to reverse the nodes between positions left and right. Use a dummy node in front of the head, walk to the node just before left, then repeatedly move the next node to the front of the sublist:

def reverse_between(head, left, right):
    dummy = ListNode(0, head)
    before = dummy
    for _ in range(left - 1):
        before = before.next
    current = before.next
    for _ in range(right - left):
        moved = current.next
        current.next = moved.next
        moved.next = before.next
        before.next = moved
    return dummy.next

The dummy node removes the special case where reversal starts at the head. The same idea of reversing sublists is used when reversing in groups of k.

Errors to Watch For

  • Returning head instead of prev at the end, which gives back the old first node, now the tail.
  • Skipping head.next = None in the recursive version, which leaves a cycle between the first two nodes.
  • Using recursion on very long lists, where Python may hit its recursion limit; prefer the iterative version in production code.
  • For a doubly linked list, forgetting to swap both next and prev on every node.

Takeaway: remember the three-pointer pattern (save next, flip link, move forward) and you can solve most reversal variations. In interviews, say the pattern out loud before coding and trace one short example; it shows clear thinking and catches mistakes early.