C语言版单向链表

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int NodeList;
struct Student
{
    //学生学号
    int id;
    //学生姓名
    char name[20];
    //分数
    int grade;
    //头指针位置
    struct Student *next;
};
//创建链表
/*
struct Student * CreateList(struct Student students[],int n)
{
    struct Student *temp;
    struct Student *head;
    for(int i=0;i<n;i++)
    {
        struct Student *p=(struct Student *)malloc(sizeof(struct Student));
        p->id=students[i].id;
        strcpy(p->name,students[i].name);
        p->grade=students[i].grade;
        p->next=NULL;
 
        if(i==0)
            head=p;
        else
            temp->next=p;
 
        temp=p;
 
    }
    return head;
//
}*/
 
struct Student * CreateNode()
{
    struct Student *temp;
    struct Student *head;
    int ExitType=0;
    while(1)
    {
        struct Student *p=(struct Student *)malloc(sizeof(struct Student));       
        int ID,Marks;
        char s[20];
        printf("请输入学号、姓名、成绩:");
        scanf("%d%s%d",&ID,&s,&Marks);
        p->id=ID;
        strcpy(p->name,s);
        p->grade=Marks;
        p->next=NULL;
 
        if(NodeList==0)
            head=p;
        else
            temp->next=p;
 
        temp=p;
        NodeList++;
        printf("需要继续输入吗?继续按1,退出按2,其他键默认也是退出!");
        scanf("%d",&ExitType);
        if(ExitType==2 || ExitType!=1)
        break;
    }   
    return head;
 
}
 
//遍历 链表
 
void ForeachNode(struct Student * head)
{
struct Student *p=head;
while(p!=NULL)
{
    printf("%d,%s,%d\n",p->id,p->name,p->grade);
    p=p->next;
}
}
 
//主函数开始
void main()
{
//静态数组
    /*
    struct Student students[3]={{1001,"Tom",90},{1002,"Tom2",90},{1003,"Tom3",90}};
    for(int i=0;i<3;i++)
    {
            printf("%d,%s,%d",students[i].id,students[i].name,students[i].grade);
    }
    */
//动态分配
    /*
struct Student *p=(struct Student *)malloc(sizeof(struct Student));
p->id=1001;
strcpy(p->name,"Test");
p->grade=95;
*/
 
//struct Student *p=(struct Student *)malloc(sizeof(struct Student));
   //struct Student students[3]={{1001,"Tom",90},{1002,"Tom2",95},{1003,"Tom3",93}};
    struct Student *head=CreateNode();
    ForeachNode(head);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值