题目
141 Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
142 Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
解法
141、给一个链表,判断它是否存在环
一个快指针fast和一个慢指针slow,两个指针都从head开始走,快指针每次走两步,慢指针每次走一步,如果两者相遇,说明有环,并且此时fast超了slow一圈,返回true,否则没有环。
如果存在环,fast先进入,在slow进入之后,fast与slow每次循环都靠近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) {
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;
}
};
142、给一个链表,如果它存在环,请返回环的起点,否则,返回NULL
快慢指针相遇后,慢指针重新指向head,然后fast和slow每次都走一步,当两者再次相遇时即为环的起点。
这里用一张网上找到的示意图来解释。图中仅列出了头结点、环起点、相遇结点。
假设快慢指针相遇与z点,则fast走过的路线为a+b+c+b,slow走过的路线为a+b,因为fast的速度是slow的两倍。所以a+b+c+b = 2*(a+b),化简可以得到a=c。
/**
* 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;
bool isCycle = false;
while(fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
if (fast == slow) {
isCycle = true;
break;
}
}
if(!isCycle)
return NULL;
slow = head;
while(fast != slow) {
fast = fast->next;
slow = slow->next;
}
return slow;
}
};