将两个按元素递增有序排列的线性表A和B,均以单链表作为存储结构,请编写算法将A表和B表归并成一个按元素值非递增有序排列的线性表C,并要求利用原表(即A和B)的结点空建构造C表。
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef struct LNode
{
struct LNode *next;
int data;
}LNode;
//用头插法建立链表
void CreateList(LNode *&A,int a[],int n)
{
LNode *s;
A=(LNode *)malloc(sizeof(LNode));
A->next=NULL;
for(int i=0;i<n;++i)
{
s=(LNode *)malloc(sizeof(LNode));
s->data=a[i];
//头插法关键
s->next=A->next;
A->next=s;
}
}
//打印链表
void ListPrint(LNode *L)
{
LNode *p;
p = L->next;
while (p) //从链表头遍历到链表尾
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int merge(LNode *A,LNode *B,LNode *&C)
{
LNode *p=A->next;
LNode *q=B->next;
LNode *s;
C=A; //初始化链表
C->next=NULL;
free(A);
while(p!=NULL&&q!=NULL)
{
if(p->data<=q->data) //尾插法,形成递减序列
{
s=p;
p=p->next;
s->next=C->next;
C->next=s;
}
else
{
s=q;
q=q->next;
s->next=C->next;
C->next=s;
}
}
while(p!=NULL)
{
s=p;
p=p->next;
s->next=C->next;
C->next=s;
}
while(q!=NULL)
{
s=q;
q=q->next;
s->next=C->next;
C->next=s;
}
}
int main()
{
int array1[10]={89,51,46,37,30,25,18,12,8,5};
int array2[10]={90,52,47,38,31,26,19,13,9,6};
LNode *A,*B,*C;
CreateList(A,array1,10);
CreateList(B,array2,10);
cout<<"A is: ";
ListPrint(A);
cout<<"B is: ";
ListPrint(B);
merge(A,B,C);
cout<<"C is: ";
ListPrint(C);
}
运行结果: