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

C语言链表程序无法显示输入列表及函数调用错误求助

C语言链表程序修复:输入列表不显示及删除函数参数错误问题

代码中的核心问题

  • 链表头指针未初始化:struct Node* node; 仅声明指针未赋值,属于野指针,会引发未定义行为。
  • 输入元素未插入链表:循环读入整数后未调用push函数,链表始终为空,导致printList无输出。
  • deleteNode参数传递错误:函数要求第二个参数为int类型,实际传入了int*类型的&key,参数类型不匹配。

修正后的完整代码

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

// A linked list node
struct Node {
    int data;
    struct Node* next;
};

/* Given a reference (pointer to pointer) to the head of a
list and an int, inserts a new node on the front of the
list. */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}

/* Given a reference (pointer to pointer) to the head of a
list and a key, deletes the first occurrence of key in
linked list */
void deleteNode(struct Node** head_ref, int key)
{
    // Store head node
    struct Node *temp = *head_ref, *prev;
 
    // If head node itself holds the key to be deleted
    if (temp != NULL && temp->data == key) {
        *head_ref = temp->next; // Changed head
        free(temp); // free old head
        return;
    }
 
    // Search for the key to be deleted, keep track of the
    // previous node as we need to change 'prev->next'
    while (temp != NULL && temp->data != key) {
        prev = temp;
        temp = temp->next;
    }
 
    // If key was not present in linked list
    if (temp == NULL)
        return;
 
    // Unlink the node from linked list
    prev->next = temp->next;
 
    free(temp); // Free memory
}

// This function prints contents of linked list starting
// from the given node
void printList(struct Node* node)
{
    while (node != NULL) {
        printf("%d  ", node->data);
        node = node->next;
    }
}

// Driver code
int main()
{
    /* Start with the empty list */
    struct Node* node = NULL;
    
    int key;
    printf("Enter 10 integers: \n");
    for(int i=0;i<10;i++){
        scanf("%d", &key);
        // 将输入的元素插入链表
        push(&node, key);
    }
    
    printf("Entered Elements within the List\n\n");
    printList(node);
     
    printf("\nEnter the element to be deleted: \n");
    scanf("%d", &key);
    
    // 修正参数传递,传入int类型的key
    deleteNode(&node, key);
    printf("\nLinked List after Deletion of %d: \n", key);
    printList(node);
    return 0;
}

关键修改说明

  1. 初始化头指针:将struct Node* node;改为struct Node* node = NULL;,确保链表从空状态开始。
  2. 插入输入元素:在输入循环内添加push(&node, key);,把每个读入的整数插入链表。
  3. 修正删除函数调用:将deleteNode(&node, &key);改为deleteNode(&node, key);,匹配函数的参数类型要求。
  4. 额外提示:当前push函数采用头插法,链表元素顺序会与输入顺序相反。如果需要保持输入顺序,可以实现尾插法的插入函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:10:27