LintCode 102. Linked List Cycle

2018-04-16  本文已影响0人  aammyytt

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

思路:
快慢指針

代碼:

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 *fast = head;
        ListNode *slow = head;
        
        while(fast->next != NULL && fast->next->next != NULL){
            fast = fast->next->next;
            slow = slow->next;
            
            if(slow == fast)
                return true;
        }
        
        return false;
        
    }
};

上一篇 下一篇

猜你喜欢

热点阅读