- leetcode 链接
- 问题描述:将两个有序链表的合并(尽量在原链表上进行)
- 编码问题分析:起初在链表类型构建过程种出现问题,导致编码失败。且该问题可分为非递归方法和递归方法实现(只是是实现了非递归方法),下面放出自己的代码以及参考的递归和非递归实现。
- 自己的c++编码
#include<iostream>
using namespace std;
#include<vector>
class Node
{
public:
int value;
Node* next;
Node(int val, Node* nd) :value(val), next(nd) {}
};
Node* merge_list(Node* a, Node* b)
{
Node* res;
Node* res_first;
if (a->value < b->value)
{
res = a;
res_first = a;
a = a->next;
res->next = NULL;
}
else
{
res = b;
res_first = b;
b = b->next;
res->next = NULL;
}
while (a != NULL && b != NULL)
{
Node* tmp;
if (a->value < b->value)
{
tmp = a;
a = a->next;
tmp->next = NULL;
res->next = tmp;
res = res->next;
}
else
{
tmp = b;
b = b->next;
tmp->next = NULL;
res->next = tmp;
res = res->next;
}
}
if (a != NULL)
{
res->next = a;
}
if (b != NULL)
res->next = b;
return res_first;
}
int main(int argc, char* argv[])
{
vector<int> a = { 1, 2, 4, 6 };
vector<int> b = { 3, 4, 7 };
Node* a0 = new Node(a[0], NULL);
Node* a1 = new Node(a[1], NULL);
Node* a2 = new Node(a[2], NULL);
Node* a3 = new Node(a[3], NULL);
Node* b0 = new Node(b[0], NULL);
Node* b1 = new Node(b[1], NULL);
Node* b2 = new Node(b[2], NULL);
a0->next = a1;
a1->next = a2;
a2->next = a3;
b0->next = b1;
b1->next = b2;
Node* res = merge_list(a0, b0);
while (res->next != NULL)
{
cout << res->value << endl;
res = res->next;
}
cout << res->value << endl;
system("pause");
return 0;
}
- 可参考的相关非递归和递归实现
- 非递归实现c++代码
#include<iostream>
using namespace std;
#include<vector>
typedef struct List_Node
{
int value;
List_Node* next;
List_Node(int val) :value(val), next(NULL) {}
};
List_Node* merge_list(List_Node* a, List_Node* b)
{
if (a == NULL)
return b;
if (b == NULL)
return a;
List_Node* pre = new List_Node(0);
List_Node* head = pre;
while (a != NULL && b != NULL)
{
if (a->value < b->value)
{
head->next = a;
a = a->next;
}
else
{
head->next = b;
b = b->next;
}
head = head->next;
}
if (a != NULL)
head->next = a;
if (b != NULL)
head->next = b;
return pre;
}
int main(int argc, char* argv[])
{
List_Node a0(1), a1(3), a2(4), a3(7);
a0.next = &a1;
a1.next = &a2;
a2.next = &a3;
List_Node b0(2), b1(2), b2(4), b3(6);
b0.next = &b1;
b1.next = &b2;
b2.next = &b3;
List_Node* res = merge_list(&a0, &b0);
while (res != NULL)
{
cout << res->value << endl;
res = res->next;
}
system("pause");
return 0;
}
- 递归实现
-
递归思考:
- 使用递归每次将指针指向值较小的节点,并递归处理其下一个节点。而结果的返回依旧是在递归回溯的过程种进行的:每次将当前递归处节点的next节点进行返回,进而可以返回当前节点,这样直至返回到最开始的调用节点,进而完成了结果链表的构建。
- 链表递归的设计类似于二叉树递归的设计:
- 1、递归出口
- 2、(满足一定条件)递归遍历a链表的next节点/递归遍历左子树
- 3、(满足一定条件)递归遍历b链表的next节点/递归遍历右子树
-
c++ 代码
-
List_Node* merge_list(List_Node* a, List_Node* b)
{
if (a == NULL)
return b;
if (b == NULL)
return a;
List_Node* pMergedHead = NULL;
if (a->value < b->value)
{
pMergedHead = a;
pMergedHead->next = merge_list(a->next, b);
}
else
{
pMergedHead = b;
pMergedHead->next = merge_list(a, b->next);
}
return pMergedHead;
}