代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LEN sizeof(struct student)
struct student
{
int num ;
int score ;
struct student *next ;
} ;
struct student *add() ;//建立无序链表
void print(struct student *a );//打印数据
struct student *sort(struct student *a );//排序
int n = 1 ;
int main (void)
{
struct student *a ;
a = add() ;
print(a ) ;
printf("after sort :\n");
a = sort(a );
print (a) ;
}
struct student *add() //建立无序链表
{
struct student *head , *p1 , *p2 ;
head = NULL ;
p1 = p2 = (struct student *)malloc(LEN) ;
do
{
printf("input num ;\n") ;
scanf("%d",&p1->num) ;
printf("input score:\n") ;
scanf("%d",&p1->score) ;
if(n == 1 )
{
if(p1->num > 0)
{
head = p1 ;
p1 = (struct student *)malloc(LEN) ;
p2->next = p1 ;
}
else
{
printf("it's a blank table!\n");
}
}
else
{
if(p1->num > 0 )
{
p2 = p1 ;
p1 = (struct student *)malloc(LEN) ;
p2->next = p1 ;
}
else
{
p2->next = NULL ;
}
}
n++;
}while( p2->next != NULL) ;
n = n-1 ;
return head ;
}
void print(struct student *a )//打印链表数据
{
struct student *p ;
p = a ;
if(p != NULL )
{
while(p)
{
printf("%d,%d\n",p->num , p->score );
p = p->next ;
}
}
else
{
printf("it's a blank table\n");
}
}
struct student *sort(struct student *a )//冒泡排序
{
struct student *head , *p , *p1 , *p2 ;//head为头指针,p为用于移动判断的结构体指针,p1为p之后的指针,p2为p之前的指针
int i , j = 0 ;
p1 = p2 = p = (struct student *)malloc(LEN) ;
head = p = p1 = p2 = a;
if(a != NULL)//判断是否为空链表
{
for(i = 0 ; i < n-1 ; i++ )//排序
{
for(j = 0 ; j < n-i-1 ; j++ )
{
if(p->next != NULL)//防止p->next->num指向不该去的地方
{
if(p->num > p->next->num)//换位
{
p1 = p->next ;
if(j == 0)
{
head = p1 ;
}
else
{
p2->next = p1 ;
}
p->next = p1->next ;
p1->next = p ;
p2 = p1 ;
}
else//移位
{
p2 = p ;
p = p->next ;
}
}
else
{
break;
}
}
p = p1 = p2 = head ;//为下一次循环排序重新赋值
}
}
else
{
printf("it's a blank table!\n");
}
return head ;
}
编译器有问题debug真难