网站建设课程 谷建,网站怎么做电子合同,中达建设网站,godaddy做网站第一种解法时哈希表#xff0c;set在使用insert插入时#xff0c;会返回一个pair#xff0c;如果pair的值为0#xff0c;则插入失败#xff0c;那么返回这个插入失败的节点#xff0c;就是入环的第一个节点#xff0c;代码如下#xff1a;
/*** Definition for singly…第一种解法时哈希表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_setListNode* 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;}
};