21. Merge Two Sorted Lists —— Python


題目:

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.

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

代碼:

於是乎,新建一個鏈表,next用兩個鏈表當前位置去比較,誰的小就放誰。當一個鏈表放完之后,說明另外一個鏈表剩下的元素都比較大,再放進去就好。

該題目簡單,因為已經是兩個排序好的鏈表了。

以下是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)  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM