Back to articles
Reverse a Linked List
How-To

Reverse a Linked List

via Dev.to TutorialJeyaprasad R

In this task, I worked on reversing a singly linked list . Given the head of a linked list, the goal is to reverse the direction of all the nodes and return the new head. What I Did I created a function reverseList that: Takes the head of a linked list Reverses the links between nodes Returns the new head of the reversed list How I Solved It Instead of creating a new list , I reversed the list in-place using an iterative approach. Approach I used three pointers: prev → keeps track of the previous node (initially None ) curr → points to the current node next_node → temporarily stores the next node Logic Behind It At each step: Store the next node → next_node = curr.next Reverse the link → curr.next = prev Move prev forward → prev = curr Move curr forward → curr = next_node Repeat this until curr becomes None . Code class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def reverseList(head): prev = None curr = head while curr: next_node = curr.next curr.ne

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
4 views

Related Articles