1.判断是否有环
很经典的数据结构入门题目,我们设置快慢指针,直接跑一遍就完事:
/**
* 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;
ListNode *fast = head;
ListNode *slow = head;
while(fast!=NULL && fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return true;
}
}
return false;
}
};
2.求取环的入口节点
这里需要一点数学上的推导:
题解写的很清楚了:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* hasCycle(ListNode *head) {
if (head == NULL)
return NULL;
ListNode *fast = head;
ListNode *slow = head;
while(fast!=NULL && fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
return slow;
}
}
return NULL;
}
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode* node = hasCycle(pHead);
if(node == NULL)
return NULL;
ListNode *pre = pHead;
while(pre != node){
pre=pre->next;
node=node->next;
}
return pre;
}
};
当然,也可以暴力来做,既然有环,我们可以循环遍历一下环求出环的节点个数k,然后设定两个速率一样的指针,一前一后,前面的领先k个节点,最后这两个指针重合就是入口节点