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

链表中环的入口结点

https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=265&tqId=39225&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D265&difficulty=undefined&judgeStatus=undefined&tags=&title=

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* EntryNodeOfLoop(ListNode* pHead) {
         //1.空间复杂度O(n)的set\hash法:遍历链表,记录节点地址是否出现过,若出现重复,则为入口节点;
        if(pHead==nullptr){
            return nullptr;
        }
        //HASH表实现、不会自动排序、增删查复杂度为O(1)
        unordered_set<ListNode*> MySet;
        for(ListNode *front = pHead; front!=nullptr; front = front->next){
            if(MySet.find(front)==MySet.end()){
                MySet.insert(front);
            }else{
                return front;
            }
        }
        return nullptr;

        //2.双指针:以下代码仅判断是否有环;
        //官方题解中具体推导环入口位置
        //https://blog.nowcoder.net/n/f80b6497aaa944ae9aadfb7307467d4e
        // for(ListNode *front = pHead->next, *behind = pHead; front!=nullptr;){
        //     if(front == behind){
        //         return front;
        //     }
        //     if(front->next == nullptr){
        //         return nullptr;
        //     }
        //     front = front->next->next;
        //     behind = behind->next;
        // }
        // return nullptr;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务