环形链表II
作者:互联网
变量简洁正确完整思路
slow每次走一步fast每次走两步,相遇,ans从起点,和slow同时走,相遇,返回相遇点 画图class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode*L=head,*R=head; bool hadCircle=false; while(R&&R->next){ L=L->next; R=R->next->next; if(L==R){ hadCircle=true; break; } } if(hadCircle){ ListNode*ans=head; while(ans!=L)ans=ans->next,L=L->next; return ans; } return nullptr; } };
标签:II,head,ListNode,hadCircle,环形,next,链表,ans,相遇 来源: https://www.cnblogs.com/zhouzihong/p/15096786.html