题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解析
- 构建列表
# -*- 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 not pHead1 and not pHead2:
return
res = []
while pHead1 and pHead2:
if pHead1.val <= pHead2.val:
res.append(pHead1)
pHead1 = pHead1.next
else:
res.append(pHead2)
pHead2 = pHead2.next
while pHead1:
res.append(pHead1)
pHead1 = pHead1.next
while pHead2:
res.append(pHead2)
pHead2 = pHead2.next
n = len(res)
for i in range(n):
if i == n - 1:
res[i].next = None
else:
res[i].next = res[i+1]
return res[0]
2. 构建两个头结点
# -*- 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
res = head = ListNode(0)
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
head.next = pHead1
pHead1 = pHead1.next
else:
head.next = pHead2
pHead2 = pHead2.next
head = head.next
if pHead1:
head.next = pHead1
if pHead2:
head.next = pHead2
return res.next