10.合并两个排序的链表
题目内容:
代码及思路:
#include<iostream>
using namespace std;
struct Linklist
{
int val;
Linklist* next;
};
class solution
{
public:
Linklist* buildlist()
{
int num;
Linklist* p1 = nullptr;
Linklist* p2 = nullptr;
Linklist* head = nullptr;
char ch;
do
{
cin >> num;
p1 = new Linklist;
p1->val = num;
if (head == nullptr)
head = p1;
else
p2->next = p1;
p2 = p1;
cin.get(ch);
} while (ch == ',');
if (head == nullptr)
return nullptr;
p2->next = nullptr;
return head;
}
Linklist* Merge(Linklist* p1,Linklist* p2)
{
if (p1 == nullptr&&p2 == nullptr)
return nullptr;
if (p1 == nullptr)
return p2;
if (p2 == nullptr)
return p1;
//两个链表都是单调递增的,要实现合并之后也是单调递增,可以利用递归的思路
Linklist* mergehead = nullptr;
if (p1->val < p2->val)
{
mergehead = p1;
mergehead->next = Merge(p1->next, p2);
}
else
{
mergehead = p2;
mergehead->next = Merge(p1, p2->next);
}
return mergehead;
}
};
void main()
{
solution* object = new solution();
Linklist* p1=object->buildlist();
Linklist* p2 = object->buildlist();
Linklist* res = object->Merge(p1, p2);
Linklist* newhead = res;
while (newhead != nullptr)
{
cout << newhead->val << endl;
newhead = newhead->next;
}
}