美文网首页
LintCode 102. Linked List Cycle

LintCode 102. Linked List Cycle

作者: aammyytt | 来源:发表于2018-04-16 00:07 被阅读0次

題目:
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;
        
    }
};

相关文章

网友评论

      本文标题:LintCode 102. Linked List Cycle

      本文链接:https://www.haomeiwen.com/subject/citskftx.html