题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* 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) {
ListNode *fast = head;
ListNode *slow = head;
if(head == NULL || head -> next == NULL || head -> next -> next == NULL) {
return false;
}
else {
while(fast != NULL && fast -> next != NULL) {
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow) {
return true;
}
}
return false;
}
}
};
经典算法:快慢指针判断链表是否有环,快指针每次前进两步,慢指针每次前进一步,如果有环,则快慢指针必定在某一时刻相遇;如果没有环,则快指针先到达链表结尾。