LeetCode-142. Linked List Cycle II

Description

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.

Follow up

Can you solve it without using extra space?

Solution 1(C++)

class Solution{
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast != nullptr && fast->next != nullptr){
            slow = slow->next;
            fast = fast->next->next;
            if(fast == slow) break;
        }
        if(fast == nullptr || fast->next == nullptr) return NULL;

        ListNode* node = head;
        while(node != slow){
            node = node->next;
            slow = slow->next;
        }
        return node;
    }
};

算法分析

其他类似的题目可参考:

这道题与上面列举的题目核心算法是一模一样的,都是找到闭合链表的起点。这种类型的题目一定要理解核心思想。

程序分析

略。

猜你喜欢

转载自blog.csdn.net/zy2317878/article/details/80794373