c - 对链表的双指针遍历感到困惑
问题描述
所以我在看这个与 Linus Torvalds 的 Ted 谈话,他在其中概述了这个例子: https ://www.youtube.com/watch?v=o8NPllzkFhE&t=14m26s
我对它很感兴趣,所以我想自己编写代码:
void remove_node(node* entry) {
node** indirect = &head;
while (*indirect != entry) {
indirect = &(*indirect)->next;
}
*indirect = entry->next;
free(entry);
}
我几乎了解所有这些,但我对这一行深感困惑:
indirect = &(*indirect)->next;
&(*indirect)
似乎采用了 dereferencing 的地址,indirect
我认为这会相互抵消,我们最终还是以 plain 结束indirect
。虽然这显然是不正确的,但我不完全明白为什么。
如果那不正确(事实并非如此),也许我只是在->
涉及时没有正确理解操作的分组/顺序。但是,无论我如何尝试将其分开,它的工作原理都不相同:
node* blegh;
while (*indirect != entry) {
// Doesn't work.
blegh = (*indirect)->next;
indirect = &blegh;
}
如果有人可以帮助我解决这个问题,我将不胜感激。
解决方案
为了理解这一行:
indirect = &(*indirect)->next;
您需要了解运算符的优先级,即了解各个运算符的执行顺序。例如:是&
在之前还是之后执行->
?
你可以在这里得到答案:https ://en.cppreference.com/w/c/language/operator_precedence
它会告诉您,您的行与以下内容相同:
indirect = &((*indirect)->next);
所以代码所做的就是获取当前节点中下一个指针的地址。因此*indirect
将是下一个指针的值(也就是指向下一个节点的指针)。
您重写代码的尝试是错误的,因为blegh
它不是列表的一部分,因此地址blegh
不是列表中任何内容的一部分。但是,您可以这样做:
node* blegh;
while (*indirect != entry) {
blegh = *indirect; // Pointer to current node
indirect = &blegh->next; // Get address of next-pointer in current node
}
推荐阅读
- python - 如何使用flask render_template API为模板文件夹中的HTML模板返回多个图像?
- python - 试图让游戏升级并使用新敌人
- regex - 涉及使用特殊字符时打印中的宽字符
- sql - SQL / SAP B1 - INV1 and RIN1 - need help only returning one line per SKU
- r - how to pass environment variable to snakemake markdown script
- javascript - Displaying API information after a button push
- firebase - method call of another class from a widget supposed to return true, but returns nothing
- spring-boot - GCP Cloud Run Spring App - How to specify flyway volume
- ruby-on-rails - How do you process a sliding window using karafka?
- django - how to create a file dynamically with OCR result from an image model