【c++】leetcode142 环形链表 II

1.题目

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

2.解法

快慢指针:

(1)当全是环时,需要判断slow==head

(2)设头结点到第一次相遇点距离为m,入环节点到相遇点为k,快指针比慢指针多走m,这个m可以是绕环n圈。slow回到head,以相同的速度再走m-k则相遇为入环节点。

代码:

/**
 * 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) {
        ListNode* fast = head;
        ListNode* slow = head;

        while (fast != NULL && fast->next != NULL)
        {
            fast = fast->next->next;
            slow = slow->next;

            if (fast == slow)
            {
                if (slow == head) return slow;
                slow = head;
                break;
            }
        }


        while (fast != NULL)
        {
            fast = fast->next;
            slow = slow->next;
            if (fast == slow)
            {
                return slow;
            }
        }
        return NULL;
    }
};

3.参考

链表入环节点的查找_zjshuster的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/qq_35975447/article/details/128793924