A和B是两个单链表 (带表头结点),其中元素递增有序。设计一个算法,将A和B归并成一个按元素值递减有序的链表C, C由A和B中的结点组成。
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode;
void createlist(LNode *&Y)
{
int n,i;
int a[100];
printf("请输入链表元素个数:\n") ;
scanf("%d",&n);
printf("请输入元素;\n"); //这里默认增序输入
for(i=0;i<n;i++)
scanf("%d",&a[i]);
LNode *s,*r;
Y=(LNode *)malloc(sizeof(LNode));
Y->next=NULL;
r=Y;
for(i=0;i<n;i++)
{
s=(LNode *)malloc(sizeof(LNode));
s->data=a[i];
r->next=s;
r=r->next;
}
r->next=NULL;
}
void sort(LNode *A,LNode *B,LNode *&C)
{
LNode *p=A->next;
LNode *q=B->next;
LNode *s;
C=A;
C->next=NULL;
free(B);
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()
{
LNode *A,*B,*C;
createlist(A);
createlist(B);
sort(A,B,C);
printf("打印排序结果:\n");
while(C->next!=NULL)
{
printf("%d ",C->next->data);
C=C->next;
}
}