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 };
复制代码

 

posted @   xiazichengxi  阅读(13)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示
主题色彩