第一種解法時哈希表,set在使用insert插入時,會返回一個pair,如果pair的值為0,則插入失敗,那么返回這個插入失敗的節點,就是入環的第一個節點,代碼如下:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode *detectCycle(ListNode *head) {unordered_set<ListNode*> set;auto cur = head;while(cur != NULL){if(set.insert(cur).second){cur = cur->next;}else{return cur;}}return NULL;}
};
第二種快慢指針的寫法,數學推導相當精妙,推到過程可以參考代碼隨想錄-環形鏈表Ⅱ
參考代碼:
class Solution {
public:ListNode *detectCycle(ListNode *head) {ListNode *slow = head, *fast = head;while (fast != nullptr) {slow = slow->next;if (fast->next == nullptr) {return nullptr;}fast = fast->next->next;if (fast == slow) {ListNode *ptr = head;while (ptr != slow) {ptr = ptr->next;slow = slow->next;}return ptr;}}return nullptr;}
};