输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
需要四个指针:最终输出、前面指针、两个列表中的指针
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if pHead1 == None:
return pHead2
if pHead2 == None:
return pHead1
newHead = pHead1 if pHead1.val < pHead2.val else pHead2
ptmp1 = pHead1
ptmp2 = pHead2
if newHead == ptmp1:
ptmp1 = ptmp1.next
else:
ptmp2 = ptmp2.next
previousPoint = newHead
while ptmp1 and ptmp2:
if ptmp1.val < ptmp2.val:
previousPoint.next = ptmp1
previousPoint = ptmp1
ptmp1 = ptmp1.next
else:
previousPoint.next = ptmp2
previousPoint = ptmp2
ptmp2 = ptmp2.next
if ptmp1 == None:
previousPoint.next = ptmp2
else:
previousPoint.next = ptmp1
return newHead