题目描述
知识点
链表、双指针
结果
实现
码前思考
- 快慢指针模板题,判断链表中是否有环
- 有两种实现循环的方法,我使用的是第一种,需要多写一个if判断,不太好,还是用第二种循环比较好。
代码实现
第一种循环
/**
* 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 == NULL){
return false;
}
//fast指针总是比slow指针快两倍
ListNode *fast = head;
ListNode *slow = head;
//只要没有碰见NULL
while(fast->next != NULL && fast->next->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};
第二种循环
我认为第二种循环更加好一些,能够让人更加好理解,而且代码也比较简单一些~
/**
* 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) {
//fast指针总是比slow指针快两倍
ListNode *fast = head;
ListNode *slow = head;
//只要没有碰见NULL
while(fast!= NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};
码后反思
- 快慢指针判断环路主要是梳理其中的循环条件~
- 快慢指针一般都是2倍速~