LeetCode题解——Linked List Cycle

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

Follow up:

Can you solve it without using extra space?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    //想法:用两个指针,一个慢指针,一个快指针,当慢指针追上快指针时,那么有cycle
    //特殊输入:空链表,两个节点的环形链表,多个节点的环形链表,普通链表
    bool hasCycle(ListNode *head) {
        if(!head) return false;
        ListNode * fast = head;
        ListNode * slow = head;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
            if(fast==slow) return true;
        }
        return false;
    }
};


你可能感兴趣的:(LeetCode,list,linked)