21. Merge Two Sorted Lists —— Python

題目:node

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.測試

沒事來作作題,該題目是說兩個排序好的鏈表組合起來,依然是排序好的,即鏈表的值從小到大。spa

代碼:code

因而乎,新建一個鏈表,next用兩個鏈表當前位置去比較,誰的小就放誰。當一個鏈表放完以後,說明另一個鏈表剩下的元素都比較大,再放進去就好。對象

該題目簡單,由於已是兩個排序好的鏈表了。blog

如下是Python代碼,並有測試過程。排序

#coding:utf-8
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 and not l2: return
        result = ListNode(0)
        l = result
        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
        #把剩餘的鏈表排在後面
        l.next = l1 or l2  
        #返回融合後鏈表從第二個對象開始,第一個對象是本身建立的ListNode(0)
        return result.next
                
if __name__=='__main__':
    #建立l1和l2兩個鏈表,注意,排序好的就須要arr1和arr2中數字從小到大
    arr1 = [1,2,3]
    arr2 = [5,6,7]
    l1 = ListNode(arr1[0])
    p1 = l1
    l2 = ListNode(arr2[0])
    p2 = l2
    for i in arr1[1:]:
        p1.next = ListNode(i)
        p1 = p1.next
    for i in arr2[1:]:
        p2.next = ListNode(i)
        p2 = p2.next    
    s=Solution()
    #融合兩個鏈表
    q=s.mergeTwoLists(l1,l2)  
相關文章
相關標籤/搜索