用cur指针来移动比较,串起排好序的链表。注意前面要记得记录一下链表初始位置(用result来记录),后面才好返回。
# 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:
cur=ListNode(-1)
result=cur#用cur移动;用result记录头,不然后面没法返回
while pHead1 and pHead2:#两个链表都非空时进入循环
if pHead1.val<=pHead2.val:
cur.next=pHead1#cur.next连pHead1
cur=cur.next#更新cur
pHead1=pHead1.next#那么pHead1可以往下走了
else:
cur.next=pHead2
cur=cur.next
pHead2=pHead2.next
#循环结束后还有链表非空,拼接未对比的链表
if pHead1:
cur.next=pHead1
else:
cur.next=pHead2
return result.next
京公网安备 11010502036488号