141. Linked List Cycle (List; Two-Pointers)

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路:采用“快慢指针”查检查链表是否含有环。让一个指针一次走一步,另一个一次走两步,如果链表中含有环,快的指针会再次和慢的指针相遇。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode* slow = head;  
        ListNode* fast = head;  
          
        while(fast && fast->next) {  
            slow = slow->next;  
            fast = fast->next->next;  
            if(slow == fast)  
                return true;  
        }  
        return false;  
    }
};

 

posted on 2015-10-03 15:53  joannae  阅读(141)  评论(0编辑  收藏  举报

导航