You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单链表指定节点后插入新节点时如何避免垃圾值问题?

问题分析与修复

错误原因

  1. 冗余节点未初始化且未正确链接:提前分配的second节点既没设置data值,也没将其next指向third,导致遍历链表时读到second的垃圾值(输出中的0),同时third节点完全没被加入链表。
  2. 插入位置错误:你期望在head之后插入8,但代码中调用insertAfter(head->next, 8)是在second节点后插入8,不符合预期逻辑。

修复后的代码

#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    struct Node *next;
};

void insertAfter(struct Node  *prevNode,int newData){
    if(prevNode == NULL){
        printf("the given previous node cannot be NULL");
        return;
    }
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = newData;
    newNode->next = prevNode->next;
    prevNode->next = newNode;
}
void printList(struct Node *head){
    while(head!=NULL){
        printf(" %d ", head->data);
        head = head->next;
    }
}


int main()
{
  struct Node* head = NULL;
  struct Node* third = NULL;
  
  head = (struct Node*)malloc(sizeof(struct Node));
  third = (struct Node*)malloc(sizeof(struct Node));

  head->data = 9;
  head->next = NULL; // 初始化head的next为NULL
  // 在head节点后插入8
  insertAfter(head, 8);
  // 配置third节点
  third->data = 10;
  third->next = NULL;
  // 将插入的新节点的next指向third,完成链表链接
  head->next->next = third;

  printf("\n Created Linked list is: ");
  printList(head);
 
  // 释放内存,避免泄漏
  struct Node* temp;
  while(head != NULL){
      temp = head;
      head = head->next;
      free(temp);
  }
  
  return 0;
}

修复说明

  • 移除了多余的second节点,insertAfter会自动创建新节点存储插入值,提前分配的second属于冗余操作,还会引入未初始化的垃圾值。
  • 调整插入目标为head节点,直接在head后插入8,符合预期的链表顺序。
  • 将插入后的新节点的next指向third,把third节点加入链表,保证遍历到10。
  • 添加了内存释放逻辑,避免内存泄漏。

内容的提问来源于stack exchange,提问作者dev0419

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 23:31:04