142.环形链表II
1 用容器set
2 用哈希表
3 用双指针法
1 class Solution { 2 public: 3 ListNode* detectCycle(ListNode* head) { 4 set<ListNode*> exclude; 5 ListNode* p,*res; 6 p = head; 7 while (p != nullptr) 8 { 9 pair<set<ListNode*>::iterator,bool> wea = exclude.emplace(p); 10 if (wea.second == false) 11 { 12 res = *(wea.first); 13 return res; 14 } 15 p = p->next; 16 } 17 return nullptr; 18 }; 19 ListNode* detectCycle1(ListNode* head) { 20 map<ListNode*,size_t> exclude; 21 ListNode* p, * res; 22 p = head; 23 while (p) 24 { 25 ++exclude[p]; 26 if (exclude[p] == 2) 27 { 28 return p; 29 } 30 p = p->next; 31 } 32 return nullptr; 33 }; 34 ListNode* detectCycle(ListNode* head) { 35 ListNode* slow = head, * fast = head; 36 while (fast != nullptr) { 37 slow = slow->next; 38 if (fast->next == nullptr) { 39 return nullptr; 40 } 41 fast = fast->next->next; 42 if (fast == slow) { 43 ListNode* ptr = head; 44 while (ptr != slow) { 45 ptr = ptr->next; 46 slow = slow->next; 47 } 48 return ptr; 49 } 50 } 51 return nullptr; 52 } 53 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理