147-21. 合併兩個有序連結串列
阿新 • • 發佈:2021-01-19
將兩個升序連結串列合併為一個新的 升序 連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。(我寫的第一個) class Solution(object): def mergeTwoLists1(self, l1, l2): """我的思路是,既然要合併,直接遍歷出來,排序重構 :type l1: ListNode :type l2: ListNode :rtype: ListNode """ temp_list = [] if l1: self.search(l1, temp_list) if l2: self.search(l2, temp_list) temp_list = sorted(temp_list, reverse=True) pre = None for i in temp_list: cur = ListNode(i) cur.next = pre pre = cur return pre def search(self, n1, temp_list): temp = n1 temp_list.append(temp.val) while temp.next: temp = temp.next temp_list.append(temp.val) def mergeTwoLists(self, l1, l2): """這個我的好,記憶體消耗小,同時執行效率高 :type l1: ListNode :type l2: ListNode :rtype: ListNode """ head = ListNode(0) a = head while l1 and l2: if l1.val < l2.val: a.next = l1 l1 = l1.next else: a.next = l2 l2 = l2.next a = a.next else: if l1: a.next = l1 else: a.next = l2 return head.next if __name__ == '__main__': root1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(4) n2.next = n3 root1.next = n2 root2 = ListNode(1) n4 = ListNode(3) n5 = ListNode(4) n4.next = n5 root2.next = n4 s1 = Solution() new_root = s1.mergeTwoLists(root1, root2) new_root.search()