天天看点

【leetcode】合并两个有序链表(python实现)

题目要求:

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
           

简单讲一下自己的思路~

首先要合并两个链表,我们就首先需要创建一个新的链表用来储存结果返回

然后对两个链表分别遍历比较大小,哪个链表的当前节点的值比较小就让他把值赋值到新链表的相应节点上,与此同时让那个链节值比较小的指向下一个节点,并且让新链表的当前节点跳到下一个,不然会永远都在赋值给第一个节点,while循环遍历即可

while l1 and l2:
            if l1.val <= l2.val:
                end.next = l1
                l1 = l1.next
            else:
                end.next = l2
                l2 = l2.next
			end = end.next
           

还有一种情况,就是当两个链表有一个为空的时候,我们就让他直接返回另一个不为空的链表即可,即

if l1:
            end.next = l1
        elif l2:
            end.next = l2
           

完整代码如下:

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        l = end= ListNode(0)
        
        while l1 and l2:
            if l1.val <= l2.val:
                end.next = l1
                l1 = l1.next
            else:
                end.next = l2
                l2 = l2.next
			end = end.next
        
        if l1:
            end.next = l1
        elif l2:
            end.next = l2
        return l.next
           

继续阅读