题解 | #牛牛队列成环#
牛牛队列成环
https://www.nowcoder.com/practice/38467f349b3a4db595f58d43fe64fcc7
1.考察知识点:
链表、快慢指针
2.编程语言:
C
3.解题思路:
定义两个快慢指针fast、slow;fast先前进2步,slow先前进1步,因为值唯一所以只需要判断fast和slow的值是否相等,即可判断fast是否可以追上slow,即存在环。循环过程仍为每次fast前进2步,slow前进1步
4.完整代码:
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return bool布尔型 */ bool hasCycle(struct ListNode* head ) { // write code here //定义快慢指针 struct ListNode *slow = head,*fast = head; while(fast && fast->next->next && fast->next) { fast = fast->next->next; slow = slow->next; if(slow->val == fast->val) { return true; } } return false; }#面试高频TOP202#