建立一个有序单向链表(新人学习)

代码如下:

#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");
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值