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;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head)
{
if(NULL == head)
return false;
struct ListNode *slow = head;
struct ListNode *fast = head->next;
while(slow && fast)
{
slow = slow->next;
fast = fast->next;
if(fast!=NULL)
fast = fast->next;
if(slow == fast)
return true;
}
return false;
}
更为清晰的解法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head)
{
if(NULL == head)
return false;
struct ListNode *slow = head;
struct ListNode *fast = head;
while(slow && fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
return false;
}
C++解法,快慢指针初始化为相同起点:
/**
* 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;
ListNode *fast = head;
while(fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast) return true;
}
return false;
}
};
C++解法,快慢指针初始化为不同起点:
/**
* 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 == nullptr || head->next == nullptr)
return false;
ListNode *slow = head;
ListNode *fast = head->next;
while(slow&&fast){
if(slow == fast) return true;
slow = slow->next;
fast = fast->next;
if(fast) fast = fast->next;
else return false;
}
return false;
}
};