首页 > 解决方案 > 对链表的双指针遍历感到困惑

问题描述

所以我在看这个与 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;
}

如果有人可以帮助我解决这个问题,我将不胜感激。

标签: cpointerslinked-list

解决方案


为了理解这一行:

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 
}

推荐阅读