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

标签 c linked-list circular-list

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

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 中,空指针的计算结果始终为 bool 值 false。参见 https://en.wikipedia.org/wiki/Null_pointer#Null_pointer .

虽然在当前逻辑下,如果列表中存在循环,则很可能没有指针为 NULL,因为我们检测到循环并从循环中跳出。 fast_p 指针可以是 NULL 只有当你的列表中没有循环并且你刚刚完成遍历整个列表以试图找到一个循环时。

enter image description here

执行顺序如下

  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

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

关于c - AND 运算符应用于链表中的指针时是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56713002/

相关文章:

ios - 将十进制转换为十六进制,添加到字节数组

c - 通过函数传递字符串会剪切前几个字符

c - 从 TP-Link 722N 获取 rx/tx 时间戳

c++ - 通过 C++ 中的另一个结构成员访问结构

c - 链表遍历节点和中间插入的两种方法

Java循环链表迭代器

双向循环链表删除节点的正确方法

c++ - 结构成员的实际总大小

python - 证明链表是循环的最快方法?在 python

c++ - 双循环链表。新节点未插入。 C++