Set the curr.next as prev which contains the curr state before this iteration
Set prev as the current rotated array
# First Iteration------
Initial head: ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 3, next: None}}}
# Create a copy of the original ListNode head
curr: ListNode{val: 1, next: ListNode{val: 2, next: ListNode{val: 3, next: None}}}
# Rotate the original head
head reset: ListNode{val: 2, next: ListNode{val: 3, next: None}}
# Set the curr.next as prev which contains the curr state before this iteration
curr: ListNode{val: 1, next: None}
# Set prev as the current rotated array
prev: ListNode{val: 1, next: None}
# Second Iteration------
Initial head: ListNode{val: 2, next: ListNode{val: 3, next: None}}
curr: ListNode{val: 2, next: ListNode{val: 3, next: None}}
head reset: ListNode{val: 3, next: None}
curr: ListNode{val: 2, next: ListNode{val: 1, next: None}}
prev: ListNode{val: 2, next: ListNode{val: 1, next: None}}
# Third Iteration-----
Initial head: ListNode{val: 3, next: None}
curr: ListNode{val: 3, next: None}
head reset: None
curr: ListNode{val: 3, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}
prev: ListNode{val: 3, next: ListNode{val: 2, next: ListNode{val: 1, next: None}}}
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
while head:
# Create a copy of the whole ListNode
curr = head
# Rotate the head LL
head = head.next
# Set the curr.next as prev which contains the curr state before this iteration
curr.next = prev
# Set prev as the current rotated array
prev = curr
return prev
Approach
https://leetcode.com/problems/reverse-linked-list/
n: number of nodes
O(n)
Search through the ListNodeO(n)
Copy of the ListNode