I.Given a linked list, determine if it has a cycle in it.
II. Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Can you solve it without using extra space?
一、两道是连着一起出的,可以说第一道题目是做第二道题目的基础,第一题也是很经典的一个题目——判断一个链表是否包含闭环。
设两个指针,一快一慢,同时步进(慢的每次步进一、快的每次步进二),那么假如快的那个最终遇到NULL,就是说明没有闭环,如果快的那一个指针,最终和慢的相遇(如果不构成环形那么一快一慢永远不会相遇),说明有闭环。
/**
* 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, *slow;
fast = slow = head;
while(fast != NULL && fast -> next != NULL){
fast = fast -> next -> next;
slow = slow -> next;
if (fast == slow)
return true;
}
return false;
}
};
二、第二题就出现了一些判断了,要求计算出环的起始位置,那么这里面又存在什么关系呢?假设链表起始位置为0,环的起始位置为L,那么slow这个指针移动了L次抵达环的起始位置的时候,fast这个指针移动了2L次,也就是说在环内移动了L次。假设此时fast位于环内K位置,并设环中有N个节点,那么fast和slow在什么位置(这里的位置以环的起始位置为0)相遇呢?这个位置是N - K。为什么是N- K呢? 因为fast每次比slow多走一步,那么fast要追上slow则需要多走从K到环起始点的步数,也就是N- K 步,那么这时每次只移动一步的slow自然就位于N-K这个位置了。那么slow再移动K次或者K的整数倍次,就可以到达环的起始位置。这个等价于从环的起始位置移动到位置K。而这个又可以等价于在环内移动了L次。这样答案就有了,在fast和slow相遇之后,令其中一个指针(我的代码中令fast)每次移动一格,又再新设一个指针从链表的head开始移动,当新指针移动到环的起始位置的时候(移动了L次),同时fast在环内移动L次,从N - K位置也移动到了环的起始点,他两重合,因此当两指针重合的时候,就是指向环的开始位置。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *cur = head;
ListNode *fast = hasCycle(head);
if (!fast)
return NULL;
while(cur != fast){
cur = cur -> next;
fast = fast -> next;
}
return cur;
}
private:
ListNode *hasCycle(ListNode *head) {
if (head == NULL)
return NULL;
ListNode *fast, *slow;
fast = slow = head;
while(fast != NULL && fast -> next != NULL){
fast = fast -> next -> next;
slow = slow -> next;
if (fast == slow)
return fast;
}
return NULL;
}
};