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

链表中环的入口结点

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;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
头像
09-05 10:14
已编辑
门头沟学院 Java
赫一鸣:我昨天投的,今天就oc了,也没和我说要面试笔试啊?不说了这单要超时了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务