142. Linked List Cycle II

来源:互联网 发布:mac铁锈红怎么样 编辑:程序博客网 时间:2024/05/01 03:57

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) {if (head == NULL) return NULL;int len = cycleLen(head);if (len == 0) return NULL;ListNode* faster = head;ListNode* slower = head;while (len--){faster = faster->next;}while (faster != slower){faster = faster->next;slower = slower->next;}return slower;}private:int cycleLen(ListNode* head){ListNode* faster = head;ListNode* slower = head;bool hasCycle = false;while (faster->next&&faster->next->next){faster = faster->next->next;slower = slower->next;if (faster == slower){hasCycle = true;break;}}if (!hasCycle) return 0;int len = 1;faster = faster->next->next;slower = slower->next;while (faster != slower){faster = faster->next->next;slower = slower->next;len++;}return len;}};


0 0
原创粉丝点击