双向链表头部插入C程序异常:单元素插入无法正常打印
双向链表头部插入单个元素无法打印的问题解决
我一眼就瞅出问题所在了——你在插入第一个节点的时候,居然忘记给节点的value赋值了!
先看你这段核心代码的问题点:
node* insert_first(node*head,int val){ if (head==NULL){ node *temp=(node*)malloc(sizeof(node)); temp->prev=NULL; temp->next=NULL; head=temp; // 这里漏掉了给temp->value赋值! } else{ node *temp=(node*) malloc(sizeof(node)); temp->value=val; // 后续节点都正确赋值了 temp->prev=NULL; temp->next=head; head->prev=temp; head=temp; } return head; }
当你插入第一个元素时,进入head==NULL的分支,虽然成功创建了节点并设置了前后指针,但没有把传入的val赋值给temp->value,这个节点的value是未初始化的垃圾值,打印的时候自然无法正常显示。而插入第二个及以后的元素时,你在else分支里正确设置了temp->value=val,所以那些节点能正常输出。
修正后的代码
只需要在第一个分支里补上赋值语句就行:
#include <stdio.h> #include <stdlib.h> // 别忘了包含malloc需要的头文件 typedef struct node{ struct node *next; struct node *prev; int value; }node; node* insert_first(node*head,int val){ if (head==NULL){ node *temp=(node*)malloc(sizeof(node)); temp->prev=NULL; temp->next=NULL; temp->value = val; // 补上这行! head=temp; } else{ node *temp=(node*) malloc(sizeof(node)); temp->value=val; temp->prev=NULL; temp->next=head; head->prev=temp; head=temp; } return head; } void print_node(node *head){ node *compteur = head; printf("list is :"); while(compteur != NULL){ printf("%d ",compteur->value); compteur = compteur->next; } } int main(){ // 标准main函数返回int类型 node *head =NULL; head = insert_first(head,1); print_node(head); return 0; // 加上返回值 }
额外的小建议
- 一定要包含
stdlib.h,malloc函数属于这个头文件,不包含的话可能会出现编译警告或者未定义行为 - 遵循C标准,
main函数的返回类型应该是int,并且最后返回0表示程序正常结束 - 后续可以添加内存释放的函数,避免长期运行导致内存泄漏
内容的提问来源于stack exchange,提问作者Haythem Tarchouna
相关产品推荐
相关产品推荐

