52-Linked List Cycle

  1. Linked List Cycle My Submissions QuestionEditorial Solution
    Total Accepted: 102785 Total Submissions: 278248 Difficulty: Easy
    Given a linked list, determine if it has a cycle in it.

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

思路:快慢指针
一个走一步,一个走两步
最后如果相遇则有环(为什么呢?,考虑在环上的情况,因为快指针走的快,走的是2步,一定可以追上慢指针,那你可能会想走两步可能直接略过慢指针啊,假设某个时刻快指针在慢指针前一个位置,下一次便相遇,若果在前2个呢,那么下一次便和慢指针相邻,回到之前的情况,前1和前2涵盖了数位奇偶,所以总言之一定会相遇)
更多的是考虑到特殊情况,为空,只有一个节点,只有两个节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL||head->next==NULL)return false;
        ListNode *p_quick=head,*p_slow=head;
        while(p_quick!=NULL&&p_quick->next!=NULL){
            p_quick = p_quick->next->next;
            p_slow = p_slow->next;
            if(p_quick==p_slow)return true;
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/freeopen/p/5482913.html