LeetCode Notes_#21 Merge Two Sorted Lists

LeetCode Notes_#21 Merge Two Sorted Lists

Contents

题目

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.

Example:

Input: 1->2->4, 1->3->4

Output: 1->1->2->3->4->4

感觉他的题目过于简单,有一些会模糊的地方没有讲清楚

  1. 输入是包含长度不同的情况的,这个要考虑;最后剩下的那一部分,直接连在最后
  2. 最后输出的整个链表也必须是顺序的(由小到大)

思路和解答

思路

思路其实跟之前的2.Add Two Numbers类似,操作链表的套路都是这样.但是不能完全抄过来,考虑一下特殊的部分

解答

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummyHead=ListNode(0)
        p=l1
        q=l2#两个链表的长度不同怎么办?
        tmpNode=dummyHead
        
        while(p!=None and q!=None):
            a=p.val 
            b=q.val 
            if a>=b:
                tmpNode.next=ListNode(b)
                q=q.next
            else:
                tmpNode.next=ListNode(a)
                p=p.next
            tmpNode=tmpNode.next   
            
        tmpNode.next=p if p!=None else q    
        
        return dummyHead.next

转载于:https://www.cnblogs.com/Howfars/p/9833181.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值