/*
* Solution.cpp
*
* Created on: 2014年4月9日
* Author: William
*/
#include <iostream>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL)
return false;
ListNode *fast = head;
ListNode *slow = NULL; // See below:
while (fast != NULL && fast != slow) {
if (slow == NULL) // We can use do..while.. to avoid this comparison trick.
slow = head;
fast = fast->next;
if (fast != NULL) {
fast = fast->next;
slow = slow->next;
}
}
if (fast == slow)
return true;
else
return false;
}
// The following function is not usable because it will damage the original linked list.
// It's not a check function!!!!
// bool hasCycle(ListNode *head) {
// ListNode *p = head;
// while (p != NULL) {
// if (p->next == head)
// return true;
// ListNode *q = p;
// // The order of next two lines is important.
// p = p->next;
// q->next = head;
// }
// return false;
// }
};
Linked List Cycle
最新推荐文章于 2022-12-06 22:57:02 发布