LeetCode 141. Linked List Cycle
Solution1:我的答案
快慢指针即可
/**
* 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;
struct ListNode *slow, *fast;
if (head->next)
slow = head->next;
else
return false;
if (head->next->next)
fast = head->next->next;
else
return false;
while (slow->next && fast->next && fast->next->next) {
if (slow == fast)
return true;
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};
Solution2:更简单的写法
参考网址:http://www.cnblogs.com/grandyang/p/4137187.html
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return true;
}
return false;
}
};