reorder_list
1from typing import Optional 2from utils import ListNode 3 4 5# @leet start 6class Solution: 7 def reorderList(self, head: Optional[ListNode]) -> None: 8 if not head: 9 return 10 11 # find the middle of the linked list 12 slow = fast = head 13 while fast and fast.next: 14 slow = slow.next 15 fast = fast.next.next 16 17 # reverse the second part of the list. 18 prev, curr = None, slow 19 while curr: 20 curr.next, prev, curr = prev, curr, curr.next 21 22 # merge two sorted linked lists 23 first, second = head, prev 24 while second.next: 25 first.next, first = second, first.next 26 second.next, second = first, second.next 27 28 29# @leet end 30 31 32def test(): 33 assert 2 + 2 == 4
class
Solution:
7class Solution: 8 def reorderList(self, head: Optional[ListNode]) -> None: 9 if not head: 10 return 11 12 # find the middle of the linked list 13 slow = fast = head 14 while fast and fast.next: 15 slow = slow.next 16 fast = fast.next.next 17 18 # reverse the second part of the list. 19 prev, curr = None, slow 20 while curr: 21 curr.next, prev, curr = prev, curr, curr.next 22 23 # merge two sorted linked lists 24 first, second = head, prev 25 while second.next: 26 first.next, first = second, first.next 27 second.next, second = first, second.next
8 def reorderList(self, head: Optional[ListNode]) -> None: 9 if not head: 10 return 11 12 # find the middle of the linked list 13 slow = fast = head 14 while fast and fast.next: 15 slow = slow.next 16 fast = fast.next.next 17 18 # reverse the second part of the list. 19 prev, curr = None, slow 20 while curr: 21 curr.next, prev, curr = prev, curr, curr.next 22 23 # merge two sorted linked lists 24 first, second = head, prev 25 while second.next: 26 first.next, first = second, first.next 27 second.next, second = first, second.next
def
test():