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?
Subscribe to see which companies asked this question
利用一個快指針,一個慢指針。如果它們能相遇,則存在環。
/**
* Language: cpp ( 9ms )
* 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||head->next==NULL){
return false;
}
ListNode* fast=head,*slow=head->next;
while(fast!=slow){
if(slow->next==NULL||slow->next->next==NULL){
return false;
}else{
fast=fast->next;
slow=slow->next->next;
}
}
return true;
}
};
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?
判斷環的入口點 :相遇點到環入口的距離等於頭節點到環入口的距離。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL||head->next==NULL){
return NULL;
}
ListNode *slow=head,*fast=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
break;
}
}
if(fast!=slow){
return NULL;
}
slow=head;
while(fast!=slow){
fast=fast->next;
slow=slow->next;
}
return fast;
}
};
計算環的長度
如何判斷兩個鏈表(不帶環)是否相交
資料參考