1、描述
141给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
来源:力扣(LeetCode)
题目一:链接:
题目2:
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、关键字
链表、环、
3、思路
快慢指针、如果一个快一个慢如果有环,一定会在追上来
如果没环一定是快指针先到终点
4、notes
1、快慢指针
2、while的条件
3、跳出循环的时机?
* 1、如果有环相等时候跳出来
* 2、如果没环,肯定是快指针先走到最后跳出来,而不是快指针和慢指针
5、复杂度
时间:O(N)没环遍历两边,有环会追上,N圈
空间:O(1)只用了两个指针
6、code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head || !head->next) return false;
auto fast = head;
auto slow = head;
// fast = fast->next; // 这里写不写都对,
while(true){
if(!fast || !fast->next){
return false;
}
fast = fast->next->next;
slow = slow->next;
if(slow == fast) break;
}
return true;
}
};
7、第二题;
如果有环把入环位置找出来
/**
* 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) {
if(!head || !head->next) return nullptr;
auto fast = head;
auto slow = head;
//fast = fast->next; // 这里如果写了就是错,不写就对,
while(true){
if(!fast || !fast->next){
return nullptr;
}
fast = fast->next->next;
slow = slow->next;
if(slow == fast) break;
}
fast = head;
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return slow;
}
};