c - c中从链表中删除条目的函数

标签 c pointers linked-list

我正在努力完成 Kochan 的《C 语言编程》一书第 10 章中的练习 4。

任务如下:

Write a function called removeEntry() to remove an entry from a linked list. The sole argument to the procedure should be a pointer to the list. Have the function remove the entry after the one pointed to by the argument.

由于某种原因,该功能无法运行。如果我在其中执行 printf() ,它似乎可以工作,但它在 main() 中不起作用。我认为如果我传递一个指针,它将改变原始指针(而不是按值传递)。但显然我做得不对。谁能帮我看看我哪里出错了?

// Function to remove an entry from a linked list

#include <stdio.h>

struct entry
{
    int value;
    struct entry *next;
};

int main(void)
{
    struct entry n1, n2, n3; // Original list

    struct entry *listPointer = &n1; // List pointer set up for iterating list

    void removeEntry(struct entry *pList);

    //listHead.next = &n1;  set list head to point to original beginning of list

    n1.value = 100;
    n1.next = &n2;

    n2.value = 200;
    n2.next = &n3;

    n3.value = 300;
    n3.next = (struct entry *) 0; // marks end of list


    // Print out values before removing entry
    printf("Before removing entry:\n");

    while (listPointer != (struct entry *) 0)
    {
        printf("%i\n", listPointer->value);
        listPointer = listPointer->next;
    }

    // reset listPointer to point to n1
    listPointer = &n1;

    // run function (DOES NOT WORK)
    removeEntry(listPointer);

    // print out values after (supposedly) removing entry
    printf("\n\nAfter removing entry:\n");

    while (listPointer != (struct entry *) 0)
    {
        printf("%i\n", listPointer->value);
        listPointer = listPointer->next;
    }

    return 0;
}

/********************* REMOVE ENTRY ********************************/

void removeEntry(struct entry *pList)
{
    //  <-------&n2
    pList = pList->next;

}

最佳答案

您的代码中存在三个误解:

首先,正如 kaylum 在他的评论中提到的,函数参数在 C 中是按值传递的。这意味着每当将参数传递给函数时,都会在函数内使用该参数的副本。当函数返回时,这个副本就会丢失。因此,您将无法按照您的意愿在 removeEntry() 中更改 pList 的值。

第二个问题(以某种方式链接)是您的函数 removeEntry() 应该删除函数参数指向的条目之后的条目。因此,如果pList指向一个条目,则应该删除pList->next指向的条目。如果你这样做,你将同时解决你的第一个问题......

第三个问题,在删除之前应该检查要删除的元素是否存在。最终,释放与您删除的元素相对应的内存,但在您的情况下,这并不适用,因为您不动态分配条目。

关于c - c中从链表中删除条目的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388481/

相关文章:

c++ - 指向抽象类型的指针数组

c - 在纯 C 中解析 .pcap 文件

c - 文件指针在传递给函数时表现不同。为什么?

c - 具有更多解的线性方程的算法

Python - 使用 ctypes 将 imgdata 指针传递给 C 中的函数

java - java中自定义链接列表的自定义值类

c++ - std::forward_list 是否支持手动重新指向?

c++ - 为什么一个循环需要 current->link !=NULL 和一个 current != NULL 用于我的链表?

c - C 中的多重链表

c++ - 写入文件原始磁盘扇区