LeetCode: Linked List Cycle II
2013-11-16 15:42
513 查看
先用双指针探到是不是有回环,假设环长为D,head到环的距离(即要找的点到head的距离)为L,慢指针走的距离为L+X,快指针比慢指针快了一个或者多个环,所以为2*(L+X),注意X < D,因为快指针比慢指针多走了一个或者多个环,所以L+X = k*D。这样解得X = k*D - L。这时离环头点距离为D-X = (1-k)*D+L。再来个节点从head开始走,都是慢指针,这样俩个指针会在环头处相遇。因为在环里的那个指针走过的距离为L,这样离环头点距离为L-(1-k)*D+L = (k-1)*D % D = 0。就是环头点。
C#
View Code
/** * 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) { ListNode *p, *q; p = q = head; if (!head || !head->next) return NULL; while (q && q->next) { p = p->next; q = q->next->next; if (p == q) break; } if (p != q) return NULL; p = head; while (p != q) { p = p->next; q = q->next; } return p; } };
C#
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode DetectCycle(ListNode head) { ListNode p = head, q = head; if (head == null || head.next == null) return null; while (q != null && q.next != null) { p = p.next; q = q.next.next; if (p == q) break; } if (p != q) return null; p = head; while (p != q) { p = p.next; q = q.next; } return p; } }
View Code
相关文章推荐
- 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-142 Linked List Cycle II
- [LeetCode] Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- [Leetcode] #141#142 Linked List Cycle I & II
- leetcode - Linked List Cycle II
- 【LeetCode】Linked List Cycle II
- leetcode之Linked List CycleII
- leetCode--linked-list-cycle-ii
- LeetCode:Linked List Cycle II
- [LeetCode] Linked List Cycle II, Solution
- [LeetCode] Linked List Cycle II 链表环起始位置
- 142 Linked List Cycle II [Leetcode]
- LeetCode Linked List Cycle II 单链表环2 (找循环起点)