2道简单+1道中等,链表的双指针相关问题就告一段落,下一步刷新的题目。
1、环形链表(难度:简单)
该题对应力扣网址
AC代码
常见思路,slow指针每次走一步,fast指针每次走两步,如果fast==slow
说明有环。
/**
* 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* slow=head,* fast=head;
while(fast && fast->next){
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
return true;
}
return false;
}
};
2、环形链表 II(难度:中等)
该题对应力扣网址
AC代码
这个方法涉及到一些简单的数学推导
大佬的原理介绍
大佬写的很清楚,我就不赘述了
/**
* 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* slow=head, * fast=head;
while(fast && fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
break;
}
}
if(fast==NULL || fast->next==NULL){
return NULL;
}
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return slow;
}
};
3、相交链表(难度:简单)
该题对应力扣网址