一道C语言链表题目

2025-04-08 22:01:46
推荐回答(2个)
回答1:

以前写的你参考下:
单向链表的建立、排序、销毁重复数据、逆序。
#include
#include
typedef struct link
{
int data;
struct link *next;
}NODE;
NODE *creast(int n)
{
NODE *head,* new,*p;
int i=1;
head=(NODE*)malloc(sizeof(NODE));
if(head)
{
printf("input the %dth number:",i);
scanf("%d",&head->data);
head->next=NULL;
p=head;
}
else
exit(0);
while(i {
new=(NODE*)malloc(sizeof(NODE));
new->next=NULL;
printf("input the %dth number:",++i);
scanf("%d",&new->data);
p->next=new;
p=new;
}
return head;
}
void output(NODE *head)
{
NODE *p;
p=head;
do
{
printf("%d",p->data);
p=p->next;
}while(p&&printf("-->"));
printf("\n");
}
NODE *contrary(NODE *head)
{
NODE *p,*q;
p=head;
while(p->next)
{
q=p->next;
p->next=q->next;
q->next=head;
head=q;
}
return head;
}
NODE *destroy(NODE *head)
{
NODE *p,*q;
p=head;
while(p->next)
{
q=p->next;
if(p->data==q->data)
{
p->next=q->next;
free(q);
}
else
p=p->next;
}
return head;
}
NODE *bubblesort (NODE *head)
{
NODE *endpt,*p,*p1,*p2;
p1=(NODE *)malloc(sizeof(NODE));
p1->next=head;
head=p1;
for(endpt=NULL;endpt!=head;endpt=p)
{
for(p=p1=head;p1->next->next!=endpt;p1=p1->next)
{
if(p1->next->data>p1->next->next->data)
{
p2=p1->next->next;
p1->next->next=p2->next;
p2->next=p1->next;
p1->next=p2;
p=p1->next->next;
}
}
}
p1=head;
head=head->next;
free(p1);
p1=NULL;
return head;
}
void main()
{
int n;
NODE *head;
printf("input the number you want to bulid(n>0):");
scanf("%d",&n);
head=creast(n);
printf("before sort:");
output(head);
printf("after sort:");
head=bubblesort(head);
output(head);
printf("after destroy:");
head=destroy(head);
output(head);
printf("after contaty:");
head=contrary(head);
output(head);
}

回答2:

main中第二个ahead=creat();改为:bhead=creat();试试
另外 你程序中好像没有排序啊。是先建立链表a、b,然后再把它们合并起来,然后输出。