C语言链表排序问题,我总是排不好,本人菜鸟,勿怪
以下贴出我的源代码,其它函数没有问题,可能编译和正常运行,可是sort_link函数就有错误了#include "stdio.h"
#include "stdlib.h"
struct node
{int data;
char name[10];
struct node *next;
};
typedef struct node LINK;
#define MAL (LINK *)malloc(sizeof(LINK))
LINK *creat_link()
{LINK *head,*s,*r;
r=head=MAL;
s=MAL;
printf("PLease input data and name:");
scanf("%d%s",&s->data,s->name);
while(1)
{r->next=s;
r=s;
s=MAL;
printf("Please input data and name:");
setbuf(stdin,NULL);
scanf("%d",&s->data);
if(s->data==-1)
break;
setbuf(stdin,NULL);
scanf("%s",s->name);
}
r->next=0;
return head;
}
void print_link(LINK *head)
{
if(head->next==0)
printf("Link is NULL!");
else
for(head=head->next;head!=0;head=head->next)
printf("%d %s\n",head->data,head->name);
}
LINK *sort_link(LINK *head)
{LINK *q,*p,*temp;
for(q=head;q->next!=0;q=q->next)
for(p=q->next;p!=0;p=p->next)
if(q->next->data>p->next->data)
{temp=p;
q->next=p->next;
q->next=temp;
temp->next=p;
}/*就是这里了,我总是写错,不知道该怎么改?*/
print_link(head);
}
main()
{LINK *head;
head=creat_link();
print_link(head);
sort_link(head);
printf("Enter anykey to exit. . .");
setbuf(stdin,NULL);
getchar();
}