leetcode-142 Linked List Cycle II

Posted tingweichen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-142 Linked List Cycle II相关的知识,希望对你有一定的参考价值。

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

想法:(1)首先的判断链表中是否有环,若有环进行(2),没有环就返回NULL

         (2)参考https://www.cnblogs.com/jack204/archive/2011/09/14/2175559.html的分析,

          从链表头到环入口点等于(n-1)循环内环+相遇点到环入口点。于是可以从链表头和相遇点分别设一个 指针,每次各走一步,两个指针必定相遇,且相遇第一点为环入口点。此时返回其中一个指针即可。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(NULL == head || head->next == NULL)
            return NULL;
        bool cycle = false; 
        struct ListNode* fast = head;
        struct ListNode* slow = head;
        while(fast  && fast->next){
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast){
                
                cycle = true;
                break;
            }
        }
        if(cycle){
            slow = head;
            while(slow != fast){
                slow = slow->next;
                fast = fast->next;
            }
            return slow;
        }

        return NULL;
    }
};

以上是关于leetcode-142 Linked List Cycle II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-142-Linked List Cycle II

leetcode-142. Linked List Cycle II

LeetCode142. Linked List Cycle II

[LeetCode] 142. Linked List Cycle II

LeetCode 142 Linked List Cycle II

leetcode 142. Linked List Cycle II