Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//思路首先:如果有环?遍历链表将无法走完,如果无环终会走到尾为NULL的位置
//让一个指针每次走一个,一个指针每次走两个位置,如果其中一个为NULL则无环,如果相遇了
//则有环
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)
return false;
ListNode *showNode=head;
ListNode *fastNode=head;
while(true)
{
if(showNode->next!=NULL)
showNode=showNode->next;
else
return false;
if(fastNode->next!=NULL && fastNode->next->next!=NULL)
fastNode=fastNode->next->next;
else
return false;
if(showNode==fastNode)
return true;
}
return false;
}
};注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50507131
原作者博客:http://blog.csdn.net/ebowtang
<LeetCode OJ> 141. Linked List Cycle
原文:http://blog.csdn.net/ebowtang/article/details/50507131