sophryu99 / algorithm

algorithm in python - 4 questions a week
4 stars 1 forks source link

206. Reverse Linked List #21

Open sophryu99 opened 1 year ago

sophryu99 commented 1 year ago

Approach

https://leetcode.com/problems/reverse-linked-list/

  1. Create a copy of the whole ListNode
  2. Rotate the head LL
  3. Set the curr.next as prev which contains the curr state before this iteration
  4. 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

n: number of nodes