题解 | #链表中环的入口结点#

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
        if (pHead == nullptr) {
            return nullptr;
        }
        ListNode *slow = pHead, *fast = pHead->next;
        int circleLen = 0, times = 1;
        // 1.查找相遇点
        while (slow != fast) {
            if (slow && fast && fast->next) {
                slow = slow->next;
                fast = fast->next->next;
            } else {
                return nullptr;
            }
        }
        // 2.存在环,则计算环长度
        while (times < 2) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                times++;
            }
            circleLen++;
        }
        // 3.slow从起点出发,fast从circleLen出发,相遇之处即为所求(环入口点)
        slow = pHead;
        fast = pHead;
        while (circleLen--) {
            fast = fast->next;
        }
        while (slow != fast) {
            slow = slow->next;
            fast = fast->next;
        }
        return slow;
    }
};

全部评论

相关推荐

牛客771574427号:恭喜你,华杰
点赞 评论 收藏
分享
offer多多的六边形战士很无语:看了你的博客,感觉挺不错的,可以把你的访问量和粉丝数在简历里提一下,闪光点(仅个人意见)
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务