1.Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断一个链表是否有环
思路:通过定义一个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) {
if(head == NULL) return false;
ListNode* fast = head;
ListNode* slow = head;
while(slow != NULL && fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(slow == fast) return true;
}
return false;
}
};
2.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?
找到环的入口节点。
思路:
1.利用第1题的思路,通过定义一个fast指针初始指向头节点,每次走两步;定义一个slow指针初始指向头节点,每次走一步。找到它们在环中相遇的节点。
此时,slow指针走了x步,fast指针走了2x步。假设圆环中有n个节点,那么2x - x = nr,也就是x = nr。r为大于0的整数。
2.假设从链表的头节点到圆环入口处经过了y个节点,那么,慢指针在圆环中经过的节点数为x-y。
根据 x = nr,慢指针还需经过y个节点,即又一次回到圆环的入口处。
所以,重新定义一个指针temp初始指向头节点,与slow节点一起,每次走一步。temp与slow相遇,即为圆环入口处。
/**
* 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) {
if(head == NULL) return NULL;
ListNode* fast = head;
ListNode* slow = head;
while(slow != NULL && fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(slow == fast){
ListNode* temp = head;
while(temp != NULL && slow != NULL){
if(slow == temp) return temp;
temp = temp->next;
slow = slow->next;
}
}
}
return NULL;
}
};