链表的创建(带头节点以及不带头节点)

基础不扎实,写一晚上才勉强写完了自己的链表创建,必须一点一点写代码才能找到自己的问题,再一点一点修正。问题再多也要一点一点面对。
#include <stdlib.h>
#include <stdio.h>
#include <malloc.h>

typedef struct student{
    int num;
    char name[20];
    struct student * next;
}listStu;

listStu* Create();

listStu* Create(){//带头节点的
    int len=0;
    int size=sizeof(listStu);
    listStu *head,*p1,*p2;

    printf("请输入要创建list的节点个数:");
    scanf("%d",&len);


    //开辟一个len大小的空间
    p2=head=(listStu*)malloc(size);

    while(len-->0){
        p1=(listStu*)malloc(size);
        printf("输入学号和姓名:");
        scanf("%d %s",&p1->num,p1->name);
        p2->next=p1;//不区分第一个和其他节点的插入
        p2=p1;
//      p1=p1->next;  这里p1不是真的在移动,而是在不停的开辟新空间
    }
    p2->next=NULL;
    return head;
}
struct student *Create1()//不带头节点的
{
    struct student *head,*p1,*p2;
    int len=0;
    int n=0;
    printf("请输入要创建list的节点个数:");
    scanf("%d",&len);

    //开辟一个LEN大小的空间,并让p1,p2指针指向它 
    p2=p1=(listStu*)malloc(sizeof(listStu));
    //将头指针置为NULL 
    head=NULL;

    //创建链表节点并给节点的元素赋值 
    printf("请输入学生的学号和姓名:");
    scanf("%ld %s",&p1->num,p1->name);
    head=p1;// 第一个节点 head = pnew; 其他ptail ->next =pnew;
    len--;
    while(p1->num!=0&&len--)
    {
        p1=(struct student *)malloc(sizeof(listStu));
        printf("请输入学生的学号和姓名:");
        scanf("%ld %s",&p1->num,p1->name);
        p2->next=p1;
        p2=p1;

    }
    //将尾节点的指针置为NULL 
    p2->next=NULL;
    return head;
}


int main(){
    Create1();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值