题目描述:
Given a linked list, determine if it has a cycle in it.
Example
Given -21->10->4->5, tail connects to node index 1, return true
Challenge
题目思路:
Follow up:
Can you solve it without using extra space?
这是一题挺有名的龟兔赛跑问题。设两个pointer,一个slow每次走一格,一个fast每次走2格。如果有circle,那么slow和fast必会在circle中的某一点相遇。否则就没有circle。
Mycode(AC = 23ms):
/**
* Definition of ListNode
* 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
if (head == NULL || head->next == NULL) {
return false;
}
ListNode *slow = head, *fast = head;
while (fast && fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
if (slow->val == fast->val) {
return true;
}
}
return false;
}
};