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;
}
};
计算环的长度
如何判断两个链表(不带环)是否相交
资料参考