标签:|| linked lse 开始 bre 地方 bsp ctc bool
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?
/** * 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) { bool cycle=false; ListNode * start=NULL; if(head==nullptr || head->next==nullptr) return start; ListNode *fast,*slow; fast=head; slow=head; while(fast->next!=nullptr && fast->next->next!=nullptr){ fast=fast->next->next; slow=slow->next; if(fast==slow){ //首先找到快慢指针相遇的地方 cycle=true; slow=head; //将其中一个指针重置为head,另一个从相遇的地方开始,然后以相同的速度前进 while(fast!=slow){ fast=fast->next; slow=slow->next;} start=fast; //再次相遇的地方就是环开始的地方 break; //记得break,不然就一直不相遇一致循环循环 } } if(cycle) return start; else return NULL; } };
标签:|| linked lse 开始 bre 地方 bsp ctc bool
原文地址:https://www.cnblogs.com/Bipolard/p/9988169.html