Linked List Cycle II(C++环形链表 II)
(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!=nullptr) {
slow=slow->next;
if(fast->next==nullptr) return nullptr;
fast=fast->next->next;
if(slow==fast) {
ListNode* temp=head;
while(temp!=slow) {
temp=temp->next;
slow=slow->next;
}
return temp;
}
}
return nullptr;
}
};
还没有评论,来说两句吧...