Пример #1
0
 def swapPairsRec(self, head: ListNode) -> ListNode:
     if not head or not head.next:
         return head
     n = head.next
     head.next = self.swapPairsRec(n.next)
     n.next = head
     return n
Пример #2
0
 def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
     s1, s2 = [], []
     while l1:
         s1.append(l1.val)
         l1 = l1.next
     while l2:
         s2.append(l2.val)
         l2 = l2.next
     dummy, carry = ListNode(), 0
     for e1, e2 in zip_longest(s1[::-1], s2[::-1]):
         s = carry
         if e1:
             s += e1
         if e2:
             s += e2
         carry = s // 10
         dummy.next = ListNode(s % 10, dummy.next)
     if carry == 1:
         dummy.next = ListNode(1, dummy.next)
     return dummy.next
Пример #3
0
 def insertionSortList(self, head: ListNode) -> ListNode:
     prev = sentinal = ListNode()
     while head:
         nxt = head.next
         # Optimization: search from begining
         # only when head is supposed in front of last insert point
         if head.val <= prev.val:
             prev = sentinal
         while prev.next and prev.next.val < head.val:
             prev = prev.next
         head.next = prev.next
         prev.next = head
         head = nxt
     return sentinal.next