提示
LintCode中的相关算法题实现代码,可以在我的GitHub中下载。
题目需求
给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
挑战
不要使用额外的空间
解题思路
使用两个指针,一个指针比另一个指针快,如果快的指针追上了慢的指针,那么就有环。
实现代码
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/*
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode * head) {
if(head==NULL) return false;
// write your code here
ListNode *p1=head;
ListNode *p2=head;
while(p1&&p2)
{
p1=p1->next;
p2=p2->next;
if(p2!=NULL)
{
p2=p2->next;
if(p1==p2) return true;
}
else
return false;
}
return false;
}
};