题目链接:
https://leetcode-cn.com/problems/linked-list-cycle-ii/
难度:中等
142. 环形链表 II
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环, 则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。
如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
说明:不允许修改给定的链表。
进阶:
你是否可以不用额外空间解决此题?
提示:
链表中节点的数目范围在范围 [0, 104] 内
-105 <= Node.val <= 105
pos 的值为 -1 或者链表中的一个有效索引
。。。。。。一言难尽
最简单直接的方法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
unordered_set<ListNode*> unset;
ListNode *detectCycle(ListNode *head) {
int i=0;
while(head!=nullptr){
if(unset.find(head)!=unset.end()){
return head;
}
unset.insert(head);
head=head->next;
}
return nullptr;
}
};
快慢指针法 这个没有想到 我知道方法 但是我以为没有办法确定开始位置 结果。。。。
fast,slow相交的时候设置一个指针ptr从链表头开始 然后使ptr和slow同步移动,slow和ptr相同的时候就是环开始的节点
/**
* 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) {
auto fast=head,slow=head;
while(fast!=nullptr){
slow=slow->next;
if(fast->next==nullptr){
return nullptr;
}
fast=fast->next->next;
// 有环必会相交
if(fast==slow){
auto res=head;
while(res!=slow){
res=res->next;
slow=slow->next;
}
return res;
}
}
return nullptr;
}
};