您的位置:首页 > 其它

lintcode 带环链表(102)

2017-02-23 09:04 302 查看
给定一个链表,判断它是否有环。

您在真实的面试中是否遇到过这个题? 

Yes

样例

给出 -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) {
// write your code here
if(head==NULL) return false;
ListNode *slow=head;
ListNode *fast=head;
while(true){
fast=fast->next;
if(fast == NULL)
return false;
if(slow == fast)
return true;
slow=slow->next;
fast=fast->next;
if(fast == NULL)
return false;
}
}
};

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: