c - 添加到列表功能

标签 c list pointers linked-list singly-linked-list

我正在尝试编写一个在列表末尾插入节点的函数。

问题是列表的最后一个节点的指针没有指向 NULL,如果我显示列表,我会从系统中得到一个错误。

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

struct node *AddToList (struct node *list, int n);

int main()
{
    struct node *node;
    node = AddToList(node, 30);
    node = AddToList(node, 20);
    node = AddToList(node, 10);
    showlist(node);
    return 0;
}

struct node *AddToList (struct node *list, int n){
    struct node *new_node;
    new_node=malloc(sizeof(struct node));
    new_node->value=n;
    new_node->next=list;
    return new_node;
};

最佳答案

是的,那是因为您插入的第一个节点 - 它是 下一个 具有值 NULL

struct node *node = NULL; //<------
node = AddToList(node, 30);
node = AddToList(node, 20);
node = AddToList(node, 10);
showlist(node);

这将解决问题。现在作为这样做的结果 - 第一次插入节点时,它的 next 将被分配值 NULL。因为第一次调用 AddToList 时,listNULL

你这样做的方式 - node 包含一些不确定的值(垃圾值)(node 是一个具有自动存储持续时间的变量)然后将其添加为 link 到第一个节点。这没有实际用处,因为现在您无法遍历列表并认为您会找到一个应该停止的 NULL 值。

来自标准章节§6.7.9

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.


您应该检查malloc 的返回值。万一它失败了——你应该处理这种情况。并在您完成使用后释放动态分配的内存。

也不确定您是如何尝试显示列表的,但是如果假设最后一个节点将指向 NULL 然后开始循环它 - 那么您在中获得了未定义的行为你的代码。

关于c - 添加到列表功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48356133/

相关文章:

c - getrlimit() 返回错误值?

c - 使用C语言在自定义shell中进行箭头键控制

c++ - 使用指针允许类充当创建另一个类实例的数据模板的缺点

c - 在 C 中用 scanf 填充数组(需要打印最后 5 个输入的数字)

编译器 gcc :error; no such file or directory

iOS + C : the use of __attribute__ ((__constructor__)) in static framework

java - 如何将 List<String> 与 String 进行比较?

python - 删除两个具有重复元素的列表之间的公共(public)元素

html - 如何设置水平 <li> 之间的空间以使其恢复 100% 的页面

c - K&R escape.. 中的练习 3-2.. 程序可以运行,但有一个小问题