A和B是两个单链表(带表头结点),其中元素递增有序。设计一个算法,将A和B归
并成一个按元素值非递减有序的链表 C,C由A 和B 中的结点组成。
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct LNode
{
int data;
struct LNode * next;
}LNode;
/**
尾插法建立单链表
*/
void createlistR(LNode *&C,int a[],int n)
{
LNode *s,*r;
C=new LNode;
C->next=NULL;
r=C;
for(int i=0;i<n;i++)
{
s=new LNode;
s->data=a[i];
r->next=s;
r=r->next;
}
r->next=NULL;
}
/****************
头插法建立单链表
*****************/
createlistF(LNode *&C,int a[],int n)
{
LNode* s;
C=new LNode;
C->next=NULL;
for(int i=0;i<n;i++)
{
s=new LNode;
s->data=a[i];
s->next=C->next;
C->next=s;
}
}
void merge1(LNode* A,LNode* B,LNode *&C)
{
LNode* p=A->next;
LNode* q=B->next;
LNode* r;//始终指向C的终端节点
C=A;
C->next=NULL;
r=C;
free(B);
while(p!=NULL&&q!=NULL)
{
if(p->data<q->data)
{
r->next=p;p=p->next;
r=r->next;
}
else
{
r->next=q;q=q->next;
r=r->next;
}
}
// r->next=NULL;
if(p!=NULL)r->next=p;
if(q!=NULL)r->next=p;
}
int main()
{
int a[]={1,4,7,8,10,15,77,90};
int b[]={1,2,3,4,5,6,9};
LNode* head1=new LNode;
createlistR(head1,a,8);
LNode* head2=new LNode;
createlistR(head2,b,7);
LNode* p=head1->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
p=head2->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl<<"*************合并后***********"<<endl;
LNode* result;
merge1(head1,head2,result);
p=result->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
return 0;
}