141. Linked List Cycle



Question

Total Accepted: 88665 Total
Submissions: 241622 Difficulty: Medium

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

Can you solve it without using extra space?

 to see which companies asked this question

Hide Tags
 Two
Pointers

Hide Similar Problems


 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 //思路首先:如果有环?遍历链表将无法走完,如果无环终会走到尾为NULL的位置
 //让一个指针每次走一个,一个指针每次走两个位置,如果其中一个为NULL则无环,如果相遇了
 //则有环
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL)
            return false;
        ListNode *showNode=head;
        ListNode *fastNode=head;
        while(true)
        {
            if(showNode->next!=NULL)
                showNode=showNode->next;
            else
                return false;
            if(fastNode->next!=NULL && fastNode->next->next!=NULL)    
                fastNode=fastNode->next->next;
            else
                return false;    
            if(showNode==fastNode)
                return true;
        }
        return false;
    }
};