LeetCode題目--合併兩個有序連結串列(python實現)
阿新 • • 發佈:2018-11-11
題目
將兩個有序連結串列合併為一個新的有序連結串列並返回。新連結串列是通過拼接給定的兩個連結串列的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4 輸出:1->1->2->3->4->4
python程式碼實現:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l=ListNode(0) f = l while l1 and l2 : if l1.val < l2.val: l.next = l1 l1=l1.next else: l.next = l2 l2 = l2.next l = l.next if l1 is not None: l.next=l1 elif l2 is not None: l.next = l2 return f.next