#include <iostream>
#include <malloc.h>
#include <vector>
using namespace std;
typedef struct Node
{
int data;
struct Node* next;
}LNode,*Linklist;
void PrintList(Linklist head)
{
Linklist tmp=head;
while(tmp!=NULL)
{
cout<<tmp->data<<" ";
tmp=tmp->next;
}
}
Linklist CreatList(Linklist head)
{
head=(Linklist)malloc(sizeof(struct Node));
LNode* node=NULL;
LNode* end=NULL;
int num;
vector<int> vec;
head->next=NULL;
end=head;
while(cin>>num){
vec.push_back(num);
if(cin.get()=='\n')
break;
}
for(int i=0;i<vec.size();i++){
node=(Linklist)malloc(sizeof(struct Node));
node->data=vec[i];
end->next=node;
end=node;
}
end->next=NULL;
return head;
}
Linklist MergeList(Linklist head1,Linklist head2)
{
Linklist mergeHead=(Linklist)malloc(sizeof(struct Node));
if(head1==NULL)
return head2;
else if(head2==NULL)
return head1;
if(head1->data<head2->data)
{
mergeHead=head1;
mergeHead->next=MergeList(head1->next,head2);
}
else if (head1->data>=head2->data)
{
mergeHead=head2;
mergeHead->next=MergeList(head1,head2->next);
}
return mergeHead;
}
int main()
{
Linklist head1,head2,head3=NULL;
head1=CreatList(head1);
head2=CreatList(head2);
head3=MergeList(head1->next,head2->next);
PrintList(head3);
return 0;
}
请编写一段代码,实现两个单向有序链表的合并
猜你喜欢
转载自blog.csdn.net/qq_40788950/article/details/88215056
今日推荐
周排行