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)  
原文地址:https://www.cnblogs.com/yuanzhaoyi/p/6124213.html