philosyang.com

206. Reverse Linked List: revisit

I must understand this approach.

 1# Definition for singly-linked list.
 2# class ListNode:
 3#     def __init__(self, val=0, next=None):
 4#         self.val = val
 5#         self.next = next
 6class Solution:
 7    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
 8        # practice in-place reversal with pointer
 9        prev = None
10        curr = head
11        
12        while curr:
13            nxt = curr.next
14            curr.next = prev
15            prev = curr
16            curr = nxt
17        
18        return prev

#Neetcode150 #Linked-List #Python