c - 为什么我在这个列表中得到垃圾值

标签 c list

我有一个单链表,节点和列表结构定义为:

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

typedef struct _list
{
   node* start;
} list;

我编写了一个函数来从列表中删除特定值的前导条目,但它似乎没有按预期工作。在运行我的函数并重新打印我的列表后,元素不再存在,而是在它的位置有一个很大的值(大约 134520848)。我删除定义值的前导值的函数是:

void removeLead(list* l, int n)
{
   node* current = l->start;
   node* temp = NULL;

   while (current->data == n)
   {
      temp = current;
      l->start = current->next;
      free(temp);
   }
}

如果我有 4 个前导值 == n 那么,在运行 removeLead() 之后,我有 3 个前导值 ~134520848。

最佳答案

代码中有错误。您没有重新分配当前变量。

void removeLead(list* l, int n)
{
   node* current = l->start;
   node* temp = NULL;

   while (current->data == n)
   {
      temp = current;
      current = current->next;
      if(l->start == temp)
          l->start = current;
      free(temp);
   }
}

关于c - 为什么我在这个列表中得到垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11131334/

相关文章:

java - 我怎样才能将一个项目 'replicate' 放入一个包含 n 个引用的列表中?

list - 列表中小于给定数字的数字

c++ - firebreath npplugin 中的文件写入权限被拒绝

c - 当变量值发生变化时,Do-while 循环会重复

C 字符串操作 : How do I append = (equal sign) to the beginning and end of a tokenized string, 由于按回车换行导致输出错误

python - 如何在 python 中打印元组列表中一列的所有值?

python - 随机播放程序(列表索引超出范围错误)

r - 将常数和所有较低的自然数 append 到列表中的数字

C系统调用I/O与sscanf实践

c - GCC 的 NetBeans 设置