题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
解题思路:使用两个指针分别指向两个链表的头结点,然后比较指针所指结点的值大小,将较小的结点作为新链表的下一个结点并移动对应的指针。
Python代码如下:
# -*- 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:
return pHead2
if not pHead2:
return pHead1
dummy = ListNode(0)
curr = dummy
while pHead1 and pHead2:
if pHead1.val < pHead2.val:
curr.next = pHead1
pHead1 = pHead1.next
else:
curr.next = pHead2
pHead2 = pHead2.next
curr = curr.next
if not pHead1:
curr.next = pHead2
else:
curr.next = pHead1
return dummy.next