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

合并两个排序的链表

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
        
            

全部评论

相关推荐

听说改名字就能收到offer哈:Radis写错了兄弟
点赞 评论 收藏
分享
10-30 22:18
已编辑
毛坦厂中学 C++
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务