题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32M,其他语言64M
解题思路
本题思路不难,就是相对来说稍微复杂一点。
我最开始想的是,合并的时候,直接把pHead2向pHead1上合并,以此来节省再次开辟新链表的内存空间。具体思路是:先找到pHead1和pHead2的较小者,假设为pHead1,然后循环遍历pHead2,将pHead2的各个节点插入到pHead1中的合适位置。
但是会存在一些问题:
- 初始时,并不能确定pHead1和pHead2的大小关系,需要分情况讨论。
- 上述的想法中对pHead2的每个节点,都需要遍历pHead1来找合适位置,本身来说比较麻烦,而且算法在最坏情况下的时间复杂度 n ∗ ( n − 1 ) n*(n-1) n∗(n−1),太高。
所以,我还是用最原始的方法,合并到一个新链表。
源代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL){
return pHead2;
}
if(pHead2==NULL){
return pHead1;
}
ListNode* pHead;//合并链表的头指针
ListNode* p; //合并链表过程中的中间指针
//初始化合并链表的头指针
if(pHead1->val<=pHead2->val){
pHead=pHead1;
pHead1=pHead1->next;
}
else{
pHead=pHead2;
pHead2=pHead2->next;
}
//合并
p=pHead;
while(pHead1!=NULL&&pHead2!=NULL){
if(pHead1->val<=pHead2->val){
p->next=pHead1;
pHead1=pHead1->next;
p=p->next;//p指针始终指向合并链表的链尾,向尾部插入节点
}
else{
p->next=pHead2;
pHead2=pHead2->next;
p=p->next;
}
}
//某一个链表合并完后,直接将另一个链表的剩余部分,链接到合并链表的链尾
if(pHead1 == NULL){
p->next = pHead2;
}
if(pHead2 == NULL){
p->next = pHead1;
}
return pHead;
}
};