LeetCode——linked-list-cycle-ii
2017-06-25 15:59
323 查看
Question
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.Follow up:
Can you solve it without using extra space?
Solution
这道题技巧性比较强,首先要判断是否有环,这个时候可以用slow-fast法(http://www.cnblogs.com/zhonghuasong/p/7077051.html),两个指针,一个一次性走一步,一个一次性走两步,如果有环的话,他们两个毕会相遇。然后就是找入口,可以看到环的起点和终点之间相隔的节点个数就是环中的节点个数,那么首先需要统计环中节点的个数。 统计好以后,怎么让slow指针走到起点的时候,fast指针走到终点呢? 也就是他们之间的距离始终保持着环中节点的个数,做法就是让fast先走环中节点个数步,然后slow和fast一起走。
Code
class Solution { public: ListNode *detectCycle(ListNode *head) { if (head == NULL) return head; ListNode* slow = head; ListNode* fast = head; //判断是否有环 while (1) { slow = slow->next; if (fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; } else { return NULL; } if (slow == fast) break; } //统计环中节点个数 int count = 1; fast = fast->next; while (slow != fast) { count++; fast = fast->next; } // 先走count步,然后一起走,相遇的地方即入口 fast = head; slow = head; while (count--) fast = fast->next; while (fast != slow) { slow = slow->next; fast = fast->next; } return slow; } };
相关文章推荐
- Leetcode: Linked List Cycle II
- [LeetCode]Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode - Linked List Cycle II
- leetcode笔记--Linked List Cycle II
- LeetCode:Linked List Cycle && Linked List Cycle II
- LeetCode Linked List Cycle II
- leetcode 日经贴,Cpp code -Linked List Cycle II
- LeetCode 142 Linked List Cycle II
- leetCode #142 Linked List Cycle II
- 【leetcode】Linked List Cycle I & II
- [C++]LeetCode: 74 Linked List Cycle II
- [LeetCode] Linked List Cycle II
- leetcode之linked List cycle && linked List cycle II
- [LeetCode] Linked List Cycle II
- LEETCODE: Linked List Cycle II
- leetcode-Linked List Cycle II-142
- LeetCode Linked List Cycle II
- leetCode:Linked List Cycle II
- LeetCode — Linked List Cycle II 解题报告