题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
        # write code here
		# 首先判空链表情况,全空,或者其中一个为空链表
        if(pHead1==None)&(pHead2==None):
            return None
        elif pHead1==None:
            return pHead2
        elif pHead2==None:
            return pHead1
		# 先找头结点
        up = pHead1
        down = pHead2
        if(pHead1.val<pHead2.val):
            head = pHead1
            up = pHead1.next
        else:
            head = pHead2
            down =pHead2.next
		# 用 cur 指针指向当前节点,用于每次添加新的节点
        cur = head
		# 任意一个链表为空就说明找完了,把剩下的表填上去就行
        while( (up!=None) & (down!=None)):
            a = up.val
            b = down.val
            if(a<b):
                temp = up
                up = up.next
            else:
                temp = down
                down = down.next
            cur.next = temp
            cur = cur.next
        while up:
            cur.next=up
            up = up.next
            cur = cur.next
        while down:
            cur.next = down
            down = down.next
            cur = cur.next
        return head
        
            

全部评论

相关推荐

点赞 评论 收藏
分享
扭转乾坤_:现在企业都是学华为,一直通过丢池子里,最后捞
点赞 评论 收藏
分享
吃不饱的肱二头肌很想退休:tnnd 我以为选妹子呢,亏我兴高采烈的冲进来😠
投递快手等公司10个岗位
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务