自己琢磨着思考了一下书上的单链表的创建案例,记录一下自己的理解
代码如下:
#include<stdio.h>
#include<stdlib.h>struct Student{char cName[20];int age;struct Student* pNext;
};
/*节点数量*/
int iCount=0;/*创建链表的函数 返回头指针*/
struct Student* create(){/*初始化链表*/struct Student* head = NULL;struct Student* pEnd,*pNew;/* 动态分配一块内存空间*/pEnd = pNew=malloc(sizeof(struct Student)); /*注意:这两个指针的值一样(即指向一样)但是地址不一样*/printf("please input the student info:");scanf("%s",&pNew->cName);scanf("%d",&pNew->age);while(pNew->age!=0){iCount++;if(iCount==1){pNew->pNext = head;pEnd=pNew;head=pNew;/*此时,三个指针指向第一个节点*/}else{pNew->pNext = NULL;pEnd->pNext=pNew;pEnd=pNew;}pNew=malloc(sizeof(struct Student)); printf("please input the student info:");scanf("%s",&pNew->cName);scanf("%d",&pNew->age);}return head;
}int main(){
create();
}
代码分析:
1、首先引入头文件stdib.h ,目的是为了使用函数 malloc。
2、定义结构体 Student
3、创建函数 create,该函数用来创建链表并且返回链表的头指针,iCount记录节点数量
4、创建指针变量head,pNew,pEnd,其中head为一个空指针
5、为指针pNew,pEnd开辟内存,指向malloc函数动态分配的内存,pNew和pEnd在内存中的地址不一样
6、为pNew所指向的Student结构体赋值
7、根据所输入的age作为循环终止条件
创建过程分析:
注意:此过程只是分析执行完选择结构的过程,其实执行之后pNew重新赋值了
最后输入一个age=0终止循环时,此时pNew指向的是一块无用的内存,可以用free函数将其释放:
free(pNew)