您的位置:首页 > 其它

带环链表-LintCode

2017-07-12 10:13 246 查看
给定一个链表,判断它是否有环。

思想:

设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇。

#ifndef C102_H
#define C102_H
#include<iostream>
using namespace std;
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
ListNode *fast = head, *slow = head;
while (fast&&fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
return true;
break;
}
}
return false;
}
};

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