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

链表中环的入口结点

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


/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution 
{
public:
    // 哈希法count函数,如果在set容器里面找到了传参的元素,返回1,否则返回0
    ListNode* EntryNodeOfLoop(ListNode* head) 
    {
        unordered_set<ListNode*> hash;
        while(head!=nullptr)
        {
		  // 进入循环先查找!这样才能确保返回环的入口!
            if(hash.count(head)) return head;// 有就返回
		  // 没有就插入元素,往后遍历!
            hash.insert(head);
            head=head->next;
        }
        return nullptr;
    }
};

全部评论

相关推荐

独特的菜鸡想要off...:今天被同一个hr捞了,姐姐你招我进去的你不记得吗
点赞 评论 收藏
分享
牛客40297450...:不是研究生强,是你强
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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