图解算法之单向链表的建立

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
struct student
{
    char name[20];
    int score;
    student *next;
};
//【1】循环建立n个单向链表函数,返回头节点
student* CreateList(student *head, int n)//n是循环次数
{
    //找到最后一个节点
    student* p = head;
    while (p->next != NULL)
    {
        p = p->next;
    }
    //
    while(n--)
    {
        student* p1 = (student*)malloc(sizeof(student));
        p->next = p1;
        scanf("%s %d",&p->name,&p->score);//数据域用户自己输入
        p1->next = NULL;//指针域指向无
        p = p1;//更新p的位置
    }
    return head;
}

//打印链表函数
void Print(student* head)
{
    student* p = head;
    int i = 0;
    while (p->next != NULL)
    {
        i++;
        printf("第%d个同学: 姓名:%s\t分数:%d\n",i, p->name, p->score);
        p = p->next;
    }
}
int main()
{
    //【1】
    int n = 4;
    student *head = (student*)malloc(sizeof(student));//head不要放东西
    //strcpy(head->name,"小明");//结构体不能直接对字符串数组赋值!!!

    head->next = NULL;//head只放指针域
    head = CreateList(head, n);
    Print(head);

    //【2】

    return 0;
}

你可能感兴趣的:(图解算法之单向链表的建立)