Linked List Cycle II
2014-01-06 11:19
281 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Follow up:
Can you solve it without using extra space?
null.
Follow up:
Can you solve it without using extra space?
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if (head==null) { return null; } ListNode pFast = head; ListNode pSlow = head; boolean first = true; while (pFast != null) { if (pSlow == pFast && !first) { //从相遇点找入口 ListNode p = head; while (p!=null) { if(p==pFast) { return p; } p = p.next; pFast = pFast.next; } } pSlow = pSlow.next; if (pFast.next !=null) { pFast = pFast.next.next; } else { pFast = null; } first = false; } return null; } }
相关文章推荐
- CODE 139: Linked List Cycle II
- 142. Linked List Cycle II
- Linked List Cycle II
- leetcode-Linked List Cycle I & II
- [leetcode][list][two pointers] Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- leetcode_c++:链表:Linked List Cycle II(142)
- Leetcode-Linked List Cycle II
- leetcode:Linked List Cycle II
- LeetCode OJ:Linked List Cycle II
- 【Leetcode】Linked List Cycle II (Walker_Runner)
- Leetcode: Linked List Cycle II
- Linked List Cycle II
- 【Leetcode】【Medium】Linked List Cycle II
- LeetCode之“链表”:Linked List Cycle && Linked List Cycle II
- 142. Linked List Cycle II
- Linked List Cycle II
- [leetcode] Linked List Cycle II
- LeetCode——Linked List Cycle II