未考虑内存,所以没有free步骤
链表的建立过程是在一个空链表的基础上逐步插入新的节点而成的。所谓空链表,即链表没有一个节点,这是链表的头指针为空。
#include<stdlib.h> 这个头文件用于malloc的运用,取得一个内存空间。
#include<stdlib.h>
struct bookdate{
int book;
struct bookdate *next;
}; //建立结构体
int main()
{
char key; //用于判断是否继续录入信息
struct bookdate *head = NULL;
struct bookdate *last = NULL;
struct bookdate *p = NULL; //head设置为头节点,last为尾节点
//p 相当于第三个容器,先把值存入p,再依次赋给head,一直到lsat。
printf("do u want to write?\n");
scanf("%c", &key);
while(key == 'y'){
p = (struct bookdate*)malloc(sizeof(struct bookdate));
if(p == NULL)
{
printf("no enough memry\n");
}
printf("write ur data\n");
scanf("%d", &p->book);
if(head == NULL){
head = p;
last = p; // last = head; 也可以
}
else{
last->next = p;
last = p;
}
p->next = NULL;
printf("again write?\n");
scanf(" %c", &key);
}
while(head != NULL){
printf("%d\n", head->book);
head = head->next;
}
return 0;
}
本文介绍了一种在C语言中创建链表的方法,并通过示例代码详细展示了如何逐步构建链表并遍历其元素。从初始化空链表开始,通过用户输入数据逐个插入节点,最终打印出链表中的所有数据。
2074

被折叠的 条评论
为什么被折叠?



