Remove Duplicates from Sorted List
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* 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) {
if(head == NULL || head->next == NULL){
return false;
}
ListNode *fast = head->next->next;
ListNode *slow = head->next;
while(fast){
if(fast == slow)
return true;
if(fast->next == NULL ){
return false;
}
fast = fast->next->next;
slow = slow->next;
}
return false;
}
};
思路:
设置两个指针,一个fast,一次往前走两步,一个slow,一次往前走一步,如果两个指针相遇则表示有环