環形鏈表 II
阿新 • • 發佈:2018-11-20
gin 思路 ctc 速度 理解 小學數學題 struct rip 其中
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) returnstart; 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; } };
環形鏈表 II