/**
* 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* dhead = new ListNode(0);
dhead->next = head;
ListNode* slow = dhead->next;
ListNode* fast = dhead->next;
while (fast != NULL && fast->next !=NULL){//保证fast能够移动两格
slow = slow->next;
fast = fast->next->next;
if (slow == fast){// 快慢指针相遇,此时从head 和 相遇点,同时查找直至相遇
ListNode* cur1 = fast;
ListNode* cur2 = dhead->next;
while (cur1 !=cur2){
cur1 = cur1->next;
cur2 = cur2->next;
}
return cur1;
}
}
return NULL;
}
};
《每日一题》142. 环形链表 II
最新推荐文章于 2023-11-13 16:26:03 发布