length = 0 while head: head = head.next length += 1 step = 1 while step < length: prev = dummy curr = dummy.next while curr: left = curr right = split(left, step) curr = split(right, step) prev = merge(left, right, prev) step *= 2 return dummy.next if __name__ == '__main__': s = Solution() head = ListNode.from_list([4, 2, 1, 3]) ans = s.sortList(head) print(ans.show()) head = ListNode.from_list([-1, 5, 3, 4, 0]) ans = s.sortList2(head) print(ans.show())
sys.path.append("..") from typing import Optional from utils import ListNode class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: n = ListNode(val=None, next=head) slow, fast = n, n.next while fast and fast.next: slow.next = fast.next temp = fast.next.next fast.next.next = fast fast.next = temp slow = fast fast = fast.next return n.next if __name__ == '__main__': s = Solution() head = ListNode.from_list([1, 2, 3, 4]) ans = s.swapPairs(head) print(ans.show())
class Solution: def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: n = ListNode(val=float("-inf"), next=head) slow, fast = n, head last = n.val while fast: if fast.next and fast.val == fast.next.val: last = fast.val fast = fast.next.next elif last == fast.val: fast = fast.next else: slow.next = fast slow = slow.next fast = fast.next slow.next = fast return n.next if __name__ == '__main__': s = Solution() head = ListNode.from_list([1, 2, 3, 3, 4, 4, 5]) ans = s.deleteDuplicates(head) print(ans.show())