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

链表节点插入代码无输出,请求排查逻辑错误

链表操作无输出问题的排查与修复

1. push 函数逻辑错误

原push函数中,先将*head赋值为新节点,再让新节点的next指向自身,形成循环链表,后续遍历会陷入死循环:

// 错误代码
*head = newnode;
newnode->next = (*head);
*head = newnode; // 重复赋值无意义

正确逻辑:先让新节点的next指向原链表头,再更新*head为新节点:

// 修正后
newnode->next = *head;
*head = newnode;

2. append 函数逻辑漏洞

当链表为空时,设置*head = newnode后未终止函数,后续代码会让新节点的next指向自身,形成循环链表:

// 错误代码
if(*head == 0){
    *head = newnode;
}
temp = *head;
while(temp->next != 0){
    temp = temp->next;
}
temp->next = newnode;

修正:在空链表处理分支内添加return,避免后续错误操作:

// 修正后
if(*head == NULL){
    *head = newnode;
    return;
}
temp = *head;
while(temp->next != NULL){
    temp = temp->next;
}
temp->next = newnode;

3. printList 函数遍历错误

原函数循环条件错误,遗漏最后一个节点的打印;且指针移动语句在循环外,导致链表根本无法遍历:

// 错误代码
void printList(struct node *temp){
    while(temp->next != NULL){
        printf("%d",temp->data);
    }
    temp = temp->next;
}

修正:循环条件改为temp != NULL,在循环内移动指针,同时添加空格匹配预期输出格式:

// 修正后
void printList(struct node *temp){
    while(temp != NULL){
        printf("%d ", temp->data);
        temp = temp->next;
    }
}

修正后的完整代码

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

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

// 头部插入
void push(struct node **head, int x){
    struct node *newnode = (struct node *)malloc(sizeof(struct node));
    newnode->data = x; 
    newnode->next = *head;
    *head = newnode;
}

// 尾部插入
void append(struct node **head, int x){
    struct node *temp;
    struct node* newnode = (struct node*)malloc(sizeof(struct node));
    newnode->data = x;
    newnode->next = NULL;
    if(*head == NULL){
        *head = newnode;
        return;
    }
    temp = *head;
    while(temp->next != NULL){
        temp = temp->next;
    }
    temp->next = newnode;
}

// 指定节点后插入
void insertAfter(struct node* temp, int x){
    if(temp == NULL){
        printf("previous node cannot be NULL");
        return;
    }
    struct node* newnode = (struct node*)malloc(sizeof(struct node));
    newnode->data = x;
    newnode->next = temp->next;
    temp->next = newnode;   
}

// 打印链表
void printList(struct node *temp){
    while(temp != NULL){
        printf("%d ", temp->data);
        temp = temp->next;
    }
}

int main(){
    struct node *head = NULL;
    append(&head,6);
    push(&head, 7);
    push(&head, 1);
    append(&head, 4);
    insertAfter(head->next, 8);
    printf("Created linked list is:\n"); 
    printList(head);
    return 0;
}

运行后会输出预期结果:

Created linked list is:
1 7 8 6 4 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:30:51