165. 合併兩個排序連結串列
阿新 • • 發佈:2020-08-09
165.合併兩個排序連結串列
中文English將兩個排序連結串列合併為一個新的排序連結串列
樣例
樣例 1:
輸入: list1 = null, list2 = 0->3->3->null
輸出: 0->3->3->null
樣例2:
輸入: list1 = 1->3->8->11->15->null, list2 = 2->null
輸出: 1->2->3->8->11->15->null
輸入測試資料(每行一個引數)如何理解測試資料?""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param l1: ListNode l1 is the head of the linked list @param l2: ListNode l2 is the head of the linked list @return: ListNode head of linked list""" def mergeTwoLists(self, l1, l2): # write your code here #初始化一個新的連結串列,迴圈,比較l1.val 和 l2.val的大小。最後,如果那個連結串列沒有取完,則直接丟進來 #初始化一個新的連結串列 dummay = ListNode(0) tail = dummay while l1 and l2: if l1.val < l2.val: #每一個賦予一個新的節點 tail.next= ListNode(l1.val) l1 = l1.next else: tail.next = ListNode(l2.val) l2 = l2.next tail = tail.next #最後,如果還剩下l1,或者l2 if l1: tail.next = l1 else: tail.next = l2 return dummay.next