环形链表一
题目链接:https://leetcode.cn/problems/linked-list-cycle/description/
使用快慢指针解决:快指针走两步,慢指针走一步
当无环时:
当有环时:
代码实现:
/**
* 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) {
ListNode* fast=head;
ListNode* slow=head;
while(fast!=nullptr&&fast->next!=nullptr){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
return true;
}
}
return false;
}
};
拓展问题:快指针走3步,慢指针走1步,快慢指针会相遇吗
答案是不一定,因为当x为偶数时,fast和slow会相遇,x-2,x-4,x-6,...0
当x为奇数时,fast和slow不会相遇,x-2,x-4,x-6,...1,-1
环形链表二
题目链接:https://leetcode.cn/problems/linked-list-cycle-ii/description/
方法一:通过数学证明求解
代码实现:
/**
* 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) {
ListNode* fast=head;
ListNode* slow=head;
while(fast!=nullptr&&fast->next!=nullptr){
slow=slow->next;
fast=fast->next->next;
if(fast==slow){
break;
}
}
if(fast==nullptr||fast->next==nullptr)return nullptr;
ListNode* meet=slow;
ListNode* cur=head;
while(meet!=cur){
meet=meet->next;
cur=cur->next;
}
return meet;
}
};
方法二:将问题转换成求两链表的相交节点
/**
* 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) {
ListNode* fast=head;
ListNode* slow=head;
while(fast!=nullptr&&fast->next!=nullptr){
slow=slow->next;
fast=fast->next->next;
if(fast==slow){
break;
}
}
if(fast==nullptr||fast->next==nullptr)return nullptr;
ListNode* meet=slow;
ListNode* newhead=meet->next;
meet->next=nullptr;
int lenA=0,lenB=0;
ListNode* curA=head;
ListNode* curB=newhead;
while(curA){
lenA++;
curA=curA->next;
}
while(curB){
lenB++;
curB=curB->next;
}
if(lenA>=lenB){
fast=head;
slow=newhead;
}else{
fast=newhead;
slow=head;
}
int cnt=abs(lenA-lenB);//绝对值
while(cnt--){
fast=fast->next;
}
while(fast!=slow){
fast=fast->next;
slow=slow->next;
}
return fast;
}
};