c - 在C中单链的后面插入

标签 c insert singly-linked-list

下面是我的节点结构声明和我在后台插入的功能。在 main 中,我声明了一个头节点并将其指向 NULL。然后我调用该函数,并尝试打印出第一个节点的值,但我的程序停止了。我仍然无法弄清楚出了什么问题。

     typedef struct node {
         int val;
         struct node *next;
     } NODE;

     void insert_back(NODE *head, int val) {
     NODE *new = malloc(sizeof(NODE));
     new->val = val;
     new->next = NULL;
         if (head == NULL)
             head = new;
         else {
             NODE *p = head;
             while (p->next != NULL)
                 p = p->next;
             p->next = new;
         }
     }


     int main() {
         NODE *head = NULL;
         insert_back(head, 2);
         printf("%d", head->val);
     }

最佳答案

当您退出函数时,您在 insert_back 中分配的指针会丢失。为了使其正常工作,您的 insert_back 应该是指针对指针。

typedef struct node {
         int val;
         struct node *next;
     } NODE;

     void insert_back(NODE **head, int val) {
     NODE *new = malloc(sizeof(NODE));
     new->val = val;
     new->next = NULL;
         if (*head == NULL)
             *head = new;
         else {
             NODE *p = *head;
             while (p->next != NULL)
                 p = p->next;
             p->next = new;
         }
     }


     int main() {
         NODE *head = NULL;
         insert_back(&head, 2);
         printf("%d", head->val);
     }

关于c - 在C中单链的后面插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22071600/

相关文章:

C、这条线是做什么的?

c - 如何通过防火墙沙箱和分析流量

使用存储过程进行具有唯一约束的 SQL 插入

database - 从 Joomla 表单字段插入数据库

c - 将节点添加到链表时出现段错误

c - 为什么 C struct tm 不是 typedef?

c - 如何使用结构创建 char** 类型的变量

mySQL插入和选择及位置问题

java - 单节点java链表中存储多个变量

swift - 如何反转 Swift 扩展中的链表?