sophryu99 / algorithm

algorithm in python - 4 questions a week

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

206. Reverse Linked List

sophryu99 opened this issue · comments

commented

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

  • Time Complexity: O(n) Search through the ListNode
  • Space Complexity: O(n) Copy of the ListNode