代码如下:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define SIZE sizeof(struct student)
struct student //¶¨Òå½á¹¹Ìå
{
int num ;
int score;
struct student *next ;
} ;
struct student *add() ;//建立有序链表
void print(struct student *a );//打印链表数据
int main (void)
{
struct student *a ;
a = add() ;
print( a ) ;
}
struct student *add()
{
struct student *head , *p , *a1 , *a2 ;//p为插入的节点,a1为p之后得节点,a2为p之前的节点
int n = 1 ;// n为节点数量
int i = 0 ;//
p = a1 = a2 = (struct student *)malloc(SIZE) ;
head = NULL ;
a1 = a2 = head ;
printf("input num :\n");
scanf("%d",&p->num);
printf("input score :\n");
scanf("%d", &p->score );
while(p->num > 0)
{
if(n == 1 )//第一次输入数据
{
if(p->num > 0)//判断是否为空链表
{
head = p ;
a2 = a1 = head ;
head->next = NULL ;
}
}
else//第一次之后
{
while( i < n-1 )//找到应该插入的地方
{
if(p->num > a2->num )
{
a2 = a1 ;
a1 = a1->next ;
i++ ;
}
else
{
break;
}
}
if(p->num < head->num ) //作为头结点
{
p->next = head ;
head = p ;
a2 = a1 = head ;
}
else
{
if(i < n-1 )//作为中间节点
{
p->next = a1 ;
a2->next = p ;
}
else//作为最后一个节点
{
p->next = NULL ;
a2->next = p ;
}
}
}
i = 0 ;
n++ ;
a2 = a1 = head ;
p = (struct student *)malloc(SIZE) ;
printf("input num :\n");
scanf("%d",&p->num);
printf("input score :\n");
scanf("%d", &p->score );
}
n = n - 1 ;
return head ;
}
void print(struct student *a )//打印链表数据
{
struct student *p ;
p = a ;
if( a != NULL)
{
while ( p )
{
printf("%d,%d\n",p->num, p->score ) ;
p = p->next ;
}
}
else
{
printf("it's a blank table");
}
}