【LeetCode】36. Linked List Cycle II

题目描述(Medium)

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?

题目链接

https://leetcode.com/problems/linked-list-cycle-ii/description/

算法分析

详见之前的文章:【剑指】23.链表中环的入口结点 

提交代码:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(!head || !head->next) return nullptr;
        ListNode *slow = head, *fast = head;
        
        while(slow && fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
            if(slow == fast)
                break;
        }
        
        // 如果没有环
        if(!fast || !fast->next)
            return nullptr;
        
        
        fast = head;
        while(slow != fast)
        {
            slow = slow->next;
            fast = fast->next;
        }
        
        return slow;
        
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/82257069
今日推荐