题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路
先创建一个新的链表表头,然后比较两个排序的链表,将较小的值接在新链表的后面,最后将排序链表有
剩余的部分直接接入链表即可。
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
#创建一个新的链表
newhead=ListNode(-1)
cur=newhead
#遍历并比较两个排序的链表的值,将值较小结点的接入新链表
while pHead1 and pHead2:
if pHead1.val<pHead2.val:
cur.next=pHead1
pHead1=pHead1.next
cur=cur.next
else:
cur.next=pHead2
pHead2=pHead2.next
cur=cur.next
#若pHead1有剩余部分
if pHead1:
cur.next=pHead1
#若pHead2有剩余部分
if pHead2:
cur.next=pHead2
return newhead.next