1: class Solution {
2: public:
3: ListNode *detectCycle(ListNode *head) {
4: ListNode *slow = head, *fast = head;
5: while (slow && fast) {
6: slow = slow->next;
7: if (fast->next == NULL) return NULL;
8: fast = fast->next->next;
9: if (slow == fast) break;
10: }
11: if (fast == NULL) return NULL;
12: fast = head;
13: while (slow != fast) {
14: slow = slow->next;
15: fast = fast->next;
16: }
17: return slow;
18: }
19: };
Saturday, June 25, 2016
142. Linked List Cycle II
I'm inspired by this blog which has very detailed explanation.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment