帶環連結串列-LintCode
阿新 • • 發佈:2019-01-29
給定一個連結串列,判斷它是否有環。
思想:
設定兩個指標(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