将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。(我写的第一个)
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()