Advertisement
DeepRest

Reorder List

Dec 22nd, 2021
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  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
  6. class Solution:
  7.     def reorderList(self, head: Optional[ListNode]) -> None:
  8.         """
  9.        Do not return anything, modify head listin-place instead.
  10.        """
  11.         #1 Locate middle
  12.         sp, fp = head, head.next
  13.         while fp and fp.next:
  14.             sp = sp.next
  15.             fp = fp.next.next
  16.        
  17.         #2 Reverse the second half
  18.         sp.next, pre, curr = None, None, sp.next
  19.         while curr:
  20.             curr.next, curr, pre = pre, curr.next, curr
  21.    
  22.         #3 Interleave the two separated halfs
  23.         curr1, curr2 = head, pre
  24.         while curr2:
  25.             curr1.next, curr2.next, curr1, curr2 = curr2, curr1.next, curr1.next, curr2.next
  26.        
  27.         return head
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement