如果知道链表环的相关前提知识,则较为方便就可以求出结果,具体分析可以查看博客http://www.cnblogs.com/xudong-bupt/p/3667729.html
代码
Linked List Cycle
class Solution{
public:
bool hasCycle(ListNode * head)
{
ListNode *slow, *fast;
if(head == NULL||head->next==NULL)
return false;
slow = head;
fast = head->next;
while(slow->next!=NULL&&fast->next&&fast->next->next!=NULL)
{
if(slow==fast)
return true;
slow = slow ->next;
fast = fast->next->next;
}
return false;
}
};
Linked List Cycle ||
代码
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow, *fast;
if(head==NULL||head->next==NULL)
return NULL;
slow = head;
fast = head;
bool flag = false;
while(slow->next!=NULL&&fast->next!=NULL&&fast->next->next!=NULL)
{
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
{
flag = true;
break;
}
}
if(flag)
{
ListNode *p;
p = head;
while(p!=slow)
{
p = p->next;
slow = slow ->next;
}
return p;
}
else
return NULL;
}
};