力扣HOT100之链表:141. 环形链表
这道题都已经刷烂了,没啥好说的,就是定义快慢指针,慢指针每次移动一步,快指针每次移动两步,如果链表中有环,那么快指针一定会追上慢指针,追上时直接返回true
,否则快指针会直接到达链表的末端,此时直接返回false
。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* slow = head, * fast = head;
while(fast && fast -> next){
slow = slow -> next;
fast = fast -> next -> next;
if(slow == fast) return true;
}
return false;
}
};