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