动态创建链表(头插法、尾插法)
今天我们来学习动态创建链表!!!
动态创建链表:分为头插法和尾插法
头插法(动态创建):
头插法就是让新节点变成头
代码如下
吐血了:这边有个非常重要的知识点,这边第三个if这里一定要将new->next初始化为NULL,因为这个if的条件就是当这个head为NULL,new做头的时候,所以此时传过来的new就是做头的,就只有它这一个,没有下一个,所以如果不初始化new里面的next的话,那么就会发生未定义的行为,就是个野指针,那么在遍历的时候,由于new->next没有初始化就会发生未定义的行为,就会发生死循环且是看不懂的循环比如:
非常的可怕!差点给我吓晕了
但是在Linux的虚拟机上面运行又不会出现这样的情况,因为windows和Linux的一些库和处理方式的不同吧,但是还是要加上new->next = NULL,这样才符合逻辑。
头插法代码
#include <stdio.h>
#include <stdlib.h>
struct Test
{
int data;
struct Test *next;
};
struct Test *insertDataBeforeHead(struct Test *head)
{
struct Test *new = NULL;
while(1){
new = (struct Test *)malloc(sizeof(struct Test));
if (new == NULL)
{
printf("内存分配失败\n");
return head;
}
printf("请输入data\n");
scanf("%d",&(new->data));
if(new->data == 0){
printf("0 quit\n");
return head;
}
if(head == NULL){
head = new;
new->next = NULL;//太关键了这个
}else{
new->next = head;
head = new;
}
}
return head;
}
void printfInfo(struct Test *head)
{
struct Test *point;
point = head;
while(point !=NULL){
printf("%d ",point->data);
point =point->next;
}
putchar('\n');
}
int main()
{
struct Test *head = NULL;
head = insertDataBeforeHead(head);
printfInfo(head);
return 0;
}
demo如上各位友友们,尽情享受......
明天学习头插法的优化补充!