from utils import ListNode class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ tmp_head = ListNode(0) tmp_head.next = head tmp = tmp_head while tmp.next and tmp.next.next: a, b = tmp.next, tmp.next.next tmp.next, a.next = b, b.next b.next = a tmp = tmp.next.next return tmp_head.next if __name__ == '__main__': s = Solution() input_l = ListNode.create([1, 2, 3, 4]) print(input_l) print(s.swapPairs(input_l))
o = r = ListNode(0) while l1 and l2: if l1.val < l2.val: r.next = ListNode(l1.val) l1 = l1.next else: r.next = ListNode(l2.val) l2 = l2.next r = r.next if l1: r.next = l1 else: r.next = l2 return o.next def mergeTwoLists2(self, l1, l2): if l1 and l2: if l1.val > l2.val: l1, l2 = l2, l1 l1.next = self.mergeTwoLists(l1.next, l2) return l1 or l2 if __name__ == '__main__': s = Solution() input_l1 = ListNode.create([1, 2, 4]) input_l2 = ListNode.create([1, 3, 4]) print(input_l1) print(input_l2) print(s.mergeTwoLists(input_l1, input_l2)) print(s.mergeTwoLists2(input_l1, input_l2))
""" def mergeTwoLists(l1, l2): if l1 and l2: if l1.val > l2.val: l1, l2 = l2, l1 l1.next = mergeTwoLists(l1.next, l2) return l1 or l2 amount = len(lists) new_lists = [] while amount > 1: for i in range(0, amount // 2): new_lists.append(mergeTwoLists(lists[i * 2], lists[i * 2 + 1])) if amount % 2: new_lists.append(lists[-1]) lists = new_lists new_lists = [] amount = len(lists) return lists[0] if amount > 0 else None if __name__ == '__main__': s = Solution() input_l1 = ListNode.create([1, 4, 5]) input_l2 = ListNode.create([1, 3, 4]) input_l3 = ListNode.create([2, 6]) print(input_l1) print(input_l2) print(input_l3) print(s.mergeKLists([input_l1, input_l2, input_l3])) print(s.mergeKLists2([input_l1, input_l2, input_l3]))