題目描述
判斷給定的鏈表中是否有環
擴展:
你能給出不利用額外空間的解法麼?
思路
快慢指針
代碼
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;
}
};