题目描述
判断给定的链表中是否有环
扩展:
你能给出不利用额外空间的解法么?
思路
快慢指针
代码
class Solution {
public:
bool hasCycle(ListNode *head) {
if (!head)
return 0;
auto fast = head, slow = head;
while(fast&&fast->next){
fast = fast->next->next;
slow = slow->next;
if (fast == slow)
return 1;
}
return 0;
}
};