AND 运算符应用于链表中的指针时是什么意思?

What does the AND operator mean when applied to pointers in linked list?

我正在尝试理解为检测和删除链表中的循环而编写的 C 代码(摘自 here)。虽然其他一切对我来说都有意义,但我无法理解 while 语句中发生的事情。更具体地说,逻辑与在应用于指针结构时表现如何?

while (slow_p && fast_p && fast_p->next) 

这里遵循了一种兔子和乌龟的方法,其中我们使用两个指针,一个快,一个慢。

/* Link list node */
struct Node 
{ 
    int data; 
    struct Node* next; 
}; 

/* Function to remove loop. Used by detectAndRemoveLoop() */
void removeLoop(struct Node *, struct Node *); 

/* This function detects and removes loop in the list 
  If loop was there in the list then it returns 1, 
  otherwise returns 0 */

int detectAndRemoveLoop(struct Node *list) 
{ 
    struct Node  *slow_p = list, *fast_p = list;

while (slow_p && fast_p && fast_p->next) 
{ 
    slow_p = slow_p->next; 
    fast_p  = fast_p->next->next; 

    /* If slow_p and fast_p meet at some point then there 
       is a loop */
    if (slow_p == fast_p) 
    { 
        removeLoop(slow_p, list); 

        /* Return 1 to indicate that loop is found */
        return 1; 
    } 
} 

/* Return 0 to indeciate that ther is no loop*/
return 0; 

}

你有一个条件,如果三个指针中的任何一个为 NULL,则确保循环中断并退出。在 C 中,空指针的计算结果始终为布尔值 false。请参阅 https://en.wikipedia.org/wiki/Null_pointer#Null_pointer

不过,根据当前的逻辑,如果您的列表中存在循环,那么 none 的指针可能会为 NULL,因为我们会检测到循环并中断循环。 fast_p 指针可能是 NULL 只有当你的列表中没有循环并且你刚刚完成遍历整个列表以试图找到一个循环时。

执行顺序如下

  1. slow_p 将在节点 2,fast_p 将在节点 3
  2. slow_p 将在节点 3,fast_p 将在节点 5
  3. slow_p 将在节点 4 并且 fast_p 将经过循环节点并再次在节点 3
  4. slow_p 将在节点 5,fast_p 将在节点 5

此时这两个指针都指向同一地址的节点,因此地址比较会断言导致函数中断,return slow_p 的地址现在是 正好指向导致这个循环的节点。