要求
- 时间限制:1秒
- 空间限制:32768K
- 热度指数:376860
- 本题知识点: 链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路
思路一:递归法
递归法思想非常巧妙。
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 pHead1 is None: return pHead2
if pHead2 is None: return pHead1
if pHead1.val <= pHead2.val:
pHead1.next = self.Merge(pHead1.next, pHead2)
return pHead1
else:
pHead2.next = self.Merge(pHead1, pHead2.next)
return pHead2
- 运行时间:30ms
- 占用内存:5724k
C++实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead2 == NULL)
return pHead1;
if (pHead1 == NULL)
return pHead2;
if (pHead1->val <= pHead2->val){
pHead1->next = Merge(pHead1->next, pHead2);
return pHead1;
}
else {
pHead2->next = Merge(pHead1, pHead2->next);
return pHead2;
}
}
};
- 运行时间:3ms
- 占用内存:400k
思路二:非递归法
比较两个链表的第一个结点值的大小,取出值较小的链表的头结点插入新链表;重复这个过程直至一个链表为空。此时再将不为空的链表接到新链表最后即结束程序。时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( 1 ) O(1) O(1)。
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
newHead = ListNode(0)
p = newHead
while pHead1 and pHead2:
if pHead1.val <= pHead2.val:
p.next = pHead1
p = p.next
pHead1 = pHead1.next
else:
p.next = pHead2
p = p.next
pHead2 = pHead2.next
if pHead1: p.next = pHead1
if pHead2: p.next = pHead2
return newHead.next
- 运行时间:48ms
- 占用内存:5756k
C++实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode newHead(0);
ListNode* p = &newHead;
while (pHead1 && pHead2){
if (pHead1->val <= pHead2->val){
p->next = pHead1;
p = p->next;
pHead1 = pHead1->next;
}
else {
p->next = pHead2;
p = p->next;
pHead2 = pHead2->next;
}
}
p->next = pHead1? pHead1:pHead2;
return newHead.next;
}
};
- 运行时间:4ms
- 占用内存:604k