HTMLify
LeetCode - Reorder List - Python
Views: 5 | Author: abh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def get_second_last(self, head) -> Optional[ListNode]: if not head or not head.next: return while head.next.next: head = head.next return head def unlink_and_get_last(self, head) -> Optional[ListNode]: second_last = self.get_second_last(head) if not second_last: return last = second_last.next second_last.next = None return last def reorderList(self, head: Optional[ListNode]) -> None: """ Do not return anything, modify head in-place instead. """ current = head while current: last = self.unlink_and_get_last(current) if not last: break last.next = current.next current.next = last current = current.next current = current.next |