题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解答
# coding:utf-8
# 创建结点
class ListNode:
def __init__(self,x, next=None):
self.val = x
self.next = next
# 合并链表
class Solution:
def Merge(self, pHead1, pHead2):
pro = 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
head.next = pHead1 or pHead2
return pro.next
pHead1 = None
pHead2 = None
# 创建链表
for i in [6,4,2]:
pHead1 = ListNode(i,pHead1)
pHead2 = ListNode(i-1,pHead2)
# 合并链表
ret = Solution().Merge(pHead1,pHead2)
验证
while ret:
print ret.val
ret = ret.next
结束