DEV Community

Mubashir
Mubashir

Posted on

Reverse A List

In this task, I worked on reversing a singly linked list. Instead of creating a new list, I reversed it in-place by changing the links between nodes.

MY APPROACH
I created a function that takes the head of a linked list and returns the reversed linked list.

EXAMPLE
Input : 1 -> 2-> 3-> 4-> 5-> NULL
Output : 5-> 4-> 3-> 2-> 1

LOGIC IMPLEMENTED
To reverse the linked list, I used an iterative approach with three pointers:
prev -> keeps track of previous node
curr -> current node
next -> stores next node temporarily

  • Initialize: prev = None curr = head
  • Traverse the list:
    • Store next node
    • Reverse the link
  • Move pointers forward
class Solution:
    def reverseList(self, head):
        prev = None
        curr = head

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

        return prev
Enter fullscreen mode Exit fullscreen mode

Top comments (0)