Reverse Linked List with explanation (c# and Python) – iterative

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

Input list: { a, b, c, d, e }
Output list: { e, d, c, b, a }

Principle

Inside an interaction conditioned by a non-null head value, we store the next node in an independent ListNode, then we cut after the head by setting head.next to newHead, update newHead to head (to be the next updated new tail) and finally set head to the stored next ListNode.

Pictorially:

Source: programmercave0.github.io
// principle reverse pointing
// 1->2->3->null ::: newHead = null | head = 1->2->3->null:
// store next (2->3->null), cut head (null<-1) take head newHead (null<-1) update head with next (2->3->null)
// (newHead) null<-1  (head) 2->3->null 
// store next (3->null), cut head (null<-2) take head newHead (null<-1<-2) update head (3->null)
// null<-1<-2  3->null 
// store next (null), cut head (null<-3) take head newHead (null<-1<-2<-3) update head (null)
// null<-1<-2<-3   

C# iterative solution

Python iterative solution

Don’t miss these tips!

We don’t spam! Read our privacy policy for more info.

Open chat
Powered by