链表:一系列结构连在一起,每一个结构体变量里面都有一个指针pNext,pNext指向下一个结构体变量,尾节点的pNext指向NULL。
静态链表:
struct students stu1 = { 1, "a", NULL };
struct students stu2 = { 2, "b", NULL };
struct students stu3 = { 3, "c", NULL };
stu3.pNext = &stu2;
stu2.pNext = &stu1;
动态内存分配:
Malloc()
void *malloc(unsigned int size)
这个函数在内存中动态开辟一块内存,unsigned int size决定内存的大小,void *空指针可以强制转换为任何类型的指针。
这个函数返回一个指针,这个指针就是开辟的内存地址。
pHead = (struct students*)malloc(sizeof(struct students));
free();
void free(void *ptr)
free:释放内存。
free(pHead);
1、怎样来创建一个链表。
创建一块内存:
struct students *pHead = NULL; //头指针
struct students *pEnd = NULL; //尾指针
pHead = (struct students *)malloc(sizeof(struct students)); //开辟头结点
printf("请输入一个学生的学号和姓名:\n");
scanf("%d%s", &pHead->number, pHead->name);
pHead->pNext = NULL;
printf("%d\n", pHead->number);