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

无递归复制链表时出现段错误,求原因分析

链表无递归复制的段错误问题修复

问题成因

你的代码在cuurent->data = temp->data;处触发段错误,核心原因是循环中非法访问空指针:

  • 进入while (temp != NULL)循环后,首先执行temp = temp->next,当temp原本是链表最后一个节点时,temp->next为NULL,此时temp被赋值为NULL
  • 后续执行cuurent->data = temp->data时,相当于访问NULL->data,直接触发段错误

除此之外,dupe函数还存在其他逻辑问题:

  • 初始节点处理后,循环构建的链表是反向的,最终复制出的链表顺序和原链表相反
  • 初始阶段对head2的赋值仅修改了函数局部变量,逻辑冗余

修复后的代码

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node* next;
};
struct node* head;
struct node* head2;

struct node* Insert(struct node* head, int x)
{
    struct node* temp = (struct node*)malloc(sizeof(struct node));
    temp->data = x;
    temp->next = head;
    return temp;
}

void Print(struct node* head)
{
    struct node* tmp1 = head;
    printf("List is:");
    while (tmp1 != NULL) {
        printf(" %d", tmp1->data);
        tmp1 = tmp1->next;
    }
    printf("\n");
}

struct node* dupe(struct node* head)
{
    if (head == NULL)
        return NULL;
    
    struct node* original = head;
    struct node* copy_head = NULL;
    struct node* copy_tail = NULL;

    // 复制第一个节点,初始化复制链表的头尾指针
    copy_head = (struct node*)malloc(sizeof(struct node));
    copy_head->data = original->data;
    copy_head->next = NULL;
    copy_tail = copy_head;
    original = original->next;

    // 循环复制剩余节点,保持原链表顺序
    while (original != NULL) {
        struct node* new_node = (struct node*)malloc(sizeof(struct node));
        new_node->data = original->data;
        new_node->next = NULL;
        copy_tail->next = new_node;
        copy_tail = new_node;
        original = original->next;
    }

    return copy_head;
}

int main(void)
{
    head = NULL;
    head2 = NULL;
    head = Insert(head, 4);
    head = Insert(head, 2);
    head = Insert(head, 3);
    head = Insert(head, 5);
    head2 = dupe(head);
    Print(head);
    Print(head2);
}

修复说明

  1. 避免空指针访问:先检查original是否为NULL,再进行节点复制操作
  2. 保持链表顺序:使用头尾指针正向构建复制链表,确保复制后的链表和原链表顺序一致
  3. 简化函数参数:去掉不必要的head2参数,函数直接返回新链表的头指针,逻辑更清晰

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:01:26