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

链表中环的入口结点

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) {
        ListNode* slow = pHead;
        ListNode* fast = pHead;
        while (fast && fast->next) {
            fast = fast->next->next;
            slow = slow->next;
            if (slow == fast) {
                break;
            }
        }
        if (fast == nullptr || fast->next == nullptr) {
            return nullptr;
        }
        slow = pHead;
        while (fast != slow) {
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
        // auto cross_node = HasCycle(pHead);
        // if (cross_node != nullptr) {
        //     return FindEntryPoint(pHead, cross_node);
        // } else {
        //     return nullptr;
        // }
    }

    ListNode* HasCycle(ListNode* pHead) {
        if (pHead == nullptr || pHead->next == nullptr) {
            return nullptr;
        }
        ListNode* slow = pHead;
        ListNode* fast = pHead->next->next;
        while (fast != nullptr) {
            if (slow == fast) {
                return fast;
            } else {
                slow = slow->next;
                fast = fast->next;
                if (fast == nullptr) {
                    return nullptr;
                } else {
                    fast = fast->next;
                }
            }
        }
        return nullptr;
    }

    ListNode* FindEntryPoint(ListNode* head, ListNode* cross_node) {
        if (head == cross_node) {
            return cross_node;
        }

        while (head != cross_node) {
            head = head->next;
            cross_node = cross_node->next;
        }

        return cross_node;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务