leetcode-141:环形链表
判断链表是否有环
/**
* 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 *slow=head,*fast=head;
while(fast!=NULL&&fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
return true;
}
}
return false;
}
};
leetcode-142:环形链表Ⅱ
返回环的起点
第一次相遇后,slow和fast都以+1的速度往后移动,再次相遇的时候就是环的起点。
/**
* 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 *slow=head,*fast=head;
while(fast&&fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast) break;
}
if(fast==NULL||fast->next==NULL) {
return NULL;
}
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return slow;
}
};
环形链表Ⅲ
返回环的长度:第一次相遇,solw走过的长度就是环的长度
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getLength(ListNode *head) {
ListNode *slow=head,*fast=head;
int length=0;
while(fast&&fast->next){
length++;
slow=slow->next;
fast=fast->next->next;
if(slow==fast) break;
}
if(fast==NULL||fast->next==NULL) {
return 0;
}
return legnth;
}
};