题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
# -*- 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
# 运行时间:23ms 占用内存:5732k
if pHead1 is None:
return pHead2
if pHead2 is None:
return pHead1
previous = pHead1 if pHead1.val < pHead2.val else pHead2
temp1 = pHead1
temp2 = pHead2
if previous == pHead1:
temp1 = temp1.next
else:
temp2 = temp2.next
while temp1 and temp2:
if temp1.val < temp2.val:
previous.next = temp1
previous = temp1
temp1 = temp1.next
else:
previous.next = temp2
previous = temp2
temp2 = temp2.next
# if temp1:
# previous.next = temp1
# else:
# previous.next = temp2
previous.next = temp1 if temp1 else temp2
return pHead1 if pHead1.val < pHead2.val else pHead2