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 @ 2023-02-23 10:55  xiazichengxi  阅读(15)  评论(0)    收藏  举报