判断链表是不是循环链表
#include<iostream>
#include<vector>
using namespace std;
/*
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution { //我的思路 错误
public:
bool hasCycle(ListNode *head) {
ListNode* faster = head;
ListNode* slower = head;
while (faster->next->next != NULL && faster->next != NULL) {
faster = faster->next->next;
slower = slower->next;
}
if (faster==slower)
return true;
return false;
}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL)
return false;
ListNode* faster = head;
ListNode* slower = head;
while(faster->next->next != NULL && faster->next != NULL) {
slower = slower->next;
faster = faster->next->next;
if (faster == slower)
return true;
}
return false;
}
};