淘宝老板叫什么名字:按从大到小顺序输入两组整数,

来源:百度文库 编辑:高校问答 时间:2024/05/03 07:58:36
按从大到小顺序输入两组整数,以结构链表存储分别输出,将两条链表按从小到大的顺序合并成一条链表再输出

/*楼上的说的容易,编写还是要发些时间的.*/
/*请把我这个程序评为最佳答案,至少我在其上发了些时间.*/

#include <stdio.h>
#include <alloc.h>
#define END 0

struct a
{
int num;
struct a* next;
};

int main ()
{
struct a head[2],*phere[2]={NULL,NULL};
struct a *temp,*presult=NULL;
int w;
int in;
int i;
for(i=0;i<2;i++)
{
/*输入两个数组,以0(在开头的#define 处可以改END为其他值)为各个数组的结束标记*/
head[i].next=NULL;
phere[i]=&head[i];
printf("input array %d one,end by zero.\n",i+1);
for(;;)
{
scanf("%d",&in);
if(in==END)break;
temp=(struct a*)(malloc(sizeof(struct a)));
temp->num=in;
temp->next=NULL;
phere[i]->next=temp;
phere[i]=temp;
}
}
printf("\n");
for(i=0;i<2;i++)
{/*分别输出两个数组*/
printf("The following is array %d\n",i+1);
for(temp=head[i].next;temp!=NULL;temp=temp->next)
{
printf("%d ",temp->num);
}
printf("\n");
}
/*归并两个数组*/
for(;head[0].next!=NULL&&head[1].next!=NULL;)
{
if(head[0].next->num<head[1].next->num)
w=1;
else
w=0;
temp=head[w].next;
head[w].next=head[w].next->next;
temp->next=presult;
presult=temp;
}
if(head[0].next==NULL)
w=1;
else
w=0;
for(;head[w].next!=NULL;)
{
temp=head[w].next;
head[w].next=head[w].next->next;
temp->next=presult;
presult=temp;
}
/*输出最后结果*/
printf("\nAfter sorting the result is:\n");
for(temp=presult;temp!=NULL;temp=temp->next)
{
printf("%d ",temp->num);
}
printf("\n");
return 0;
}

先把数据输到2个链表里!
然后用2个循环把表头的数据插到表尾,这样每个链表都是从小到大了!
最后用一个循环分别从头挑选小的元素!