Leetcode::Linked List Cycle
思想:使用两个指针,一个指针每次走一步,另一个每次走两步,如果走两步的追上走一步的指针,则存在环。
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
bool result = false;
if( head )
{
ListNode * first = head;
ListNode * second = head;
do
{
first = first->next;
if( second->next == NULL || second->next->next == NULL )
return result;
second = second->next->next;
}while( first != second );
result = true;
}
return result;
}
};

浙公网安备 33010602011771号