问题描述:
Given a linked list, determine if it has a cycle in it.
问题分析:
本题目要求一个链表中是否存在环。我们可以采取双指针遍历的方式,一个fast指针每次遍历两步,一个slow指针每次遍历一步,如果链表中存在环的话,fast早晚能追上slow。
过程详见代码:
/**
* 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 || head -> next == NULL) return false;
ListNode *fast = head;
ListNode *slow = head;
while(slow->next && fast->next && fast->next->next)
{
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow)
return true;
}
return false;
}
};