链表排序
int main()
{
struct student
{
int num;
float score;
struct student * next;
};
struct student a,b,c,d,e,f,g,*head1=NULL,*head=NULL,*p=NULL,*p1=NULL,*p2=NULL,*p3=NULL,*x=NULL,*y=NULL;
a.num=10101;a.score=89.5;
b.num=10103;b.score=90;
c.num=10107;c.score=85;
d.num=10102;d.score=91;
f.num=10104;f.score=92;
g.num=10108;g.score=95;
head=&a;a.next=&b;
b.next=&c;c.next=&d;
d.next=&e;
e.next=&f;f.next=&g;
g.next=NULL;x=NULL;
int i,j;
p=head->next;
head1=&a;
p1=&a;p2=&a;
for(i=0;i<5;i++)
{
if(p->num<head1->num)
head1=p;
p=p->next;
}
p=head->next;
for(i=0;i<5;i++)
{
for(j=i;j<5;j++)
{
if(p->num<p2->num)
{
p2=p;
p3=p1;
}
p1=p1->next;
p=p->next;
}
if(p2==head)
y=p3->next;
p3->next=p3->next->next;
x=p->next;
p->next=y;
p2->next=x;
p=head;p1=&a;p2=&a;
}
p=head1;
do
{
printf("%d %f \n",p->num,p->score);
p=p->next;
}while(p=!NULL);
return 0;
}
我编译通过了 但是总是执行不了
我是第一次写链表排序 不知道这么弄正不正确
麻烦大神们纠正一下咯 展开
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
int num;
float score;
struct student *next;
}STU,*NODE;
NODE CreateLink() {
NODE head,p,q;
head = p = (NODE)malloc(sizeof(student));
for(int i = 0;i < 7;++i) {
q = (NODE)malloc(sizeof(student));
printf("第%d个学生的学号 : ",i + 1);
scanf("%d",&q->num);
printf("第%d个学生的成绩 : ",i + 1);
scanf("%f",&q->score);
p->next = q;
p = q;
}
p->next = NULL;
return head;
}
void PrintLink(NODE head) {
NODE p = head->next;
while(p != NULL) {
printf("学号 : %d\t成绩 : %.2f\n",p->num,p->score);
p = p->next;
}
printf("\n");
}
void SortLink_score(NODE head) {
NODE p,s,pt;
p = head;
s = p->next;
while(p->next != NULL) {
while(s->next != NULL) {
if(p->next->score < s->next->score) {
pt = p->next;
p->next = s->next;
s->next = p->next->next;
p->next->next = pt;
}
else s = s->next;
}
p = p->next;
s = p->next;
}
}
void FreeLink(NODE head) {
NODE p,q;
p = head;
q = p->next;
while(q != NULL) {
p = q;
q = p->next;
free(p);
}
free(head);
}
int main() {
NODE head = CreateLink();
printf("排序前 :\n");
PrintLink(head);
SortLink_score(head);
printf("排序后 :\n");
PrintLink(head);
FreeLink(head);
return 0;
}
我看懂了 不过我调用排序函数以后 为什么出现0x00000005的错误呀 急死了 大神再教教咯
如果是调用我贴上去的排序函数有问题,则可能是你创建链表时出现了问题,请检查!