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

C语言循环单链表头插法实现时后续节点丢失问题如何解决?

问题原因定位

你的代码存在三处核心逻辑错误,直接导致节点丢失、链表不符合循环结构要求:

  • 首节点初始化不符合循环单链表规则:首次插入节点时p->next = start,此时start为NULL,导致首节点的next指针指向NULL而非自身,无法构成循环结构。
  • 头插逻辑错误:非首节点插入时,你写的p->next = start->next并没有将新节点和原有头节点关联,反而直接跳过了原有头节点,导致之前插入的所有节点直接丢失。正确的头插逻辑应该是新节点的next指向当前的头节点start,再更新头节点为新节点。
  • 缺少尾节点指向头节点的处理:循环单链表要求尾节点的next指向头节点,你的代码全程没有处理这一逻辑,会导致遍历链表时出现越界访问。
修复后的完整代码
#include <stdio.h>
#include <stdlib.h>

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

int main()
{
    struct node *start, *p, *tail = NULL;
    int n;
    printf("Enter length of list: ");
    scanf(" %i", &n);
    start = NULL;
    for (int i = 0; i < n; i++)
    {
        p = malloc(sizeof(struct node));
        printf("Enter data: ");
        scanf(" %i", &p->data);
        if (start == NULL)
        {
            // 首节点先临时指向自身构成循环
            p->next = p;
            start = p;
            tail = p; // 头插场景下第一个插入的节点永远是尾节点,直接记录避免后续遍历查找
        }
        else
        {
            // 正确头插逻辑:新节点指向原有头节点
            p->next = start;
            start = p;
        }
    }
    // 尾节点指向新头节点,完成循环链表结构
    tail->next = start;

    p = start;
    printf("List entered is: ");
    for (p = start; p->next != start; p = p->next)
    {
        printf("%i\t", p->data);
    }
    printf("%i", p->data);

    // 补充内存释放逻辑,避免内存泄漏
    p = start;
    struct node *temp;
    do {
        temp = p->next;
        free(p);
        p = temp;
    } while(p != start);

    return 0;
}

内容的提问来源于stack exchange,提问作者just_another 3d_object

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:57:03