52、链表中环的入口结点

题目描述:

  给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

解题思路:

  假设存在环,fast以速度2运行,slow以速度1运行,在slow走到入口t时,如图(m1为在slow首次到t时fast的位置,a为h到t的距离,b为t到m1的距离,n为环的周长):
在这里插入图片描述
  由图知fast走的距离为a+b+xn,slow走的距离为a+b,又v(fast) = 2v(slow),所以x(fast) = 2x(slow),即2(a+b) = a+b+xn,因此a = xn-b,而m1逆时针到t的距离为n-b。

Demo:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead){
        ListNode *pslow = pHead;
        ListNode *pfast = pHead;
        while (pfast != nullptr && pfast->next != nullptr){
            // 定义两个快慢指针
            pslow = pslow->next;
            pfast = pfast->next->next;
            // 记录下第一次相遇的位置
            if (pslow == pfast){
                // 将慢指针指向头结点
                pslow = pHead;
                while (pfast != pslow){
                    // 这次让两个指针前进的速度一样,当他们再次相遇时,即为入口结点
                    pslow = pslow->next;
                    pfast = pfast->next;
                }
                return pslow;
            }
        }
        return nullptr;
    }
};

猜你喜欢

转载自blog.csdn.net/daaikuaichuan/article/details/89763040