我有一个单链表,节点和列表结构定义为:
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/