【LeetCode OJ】Linked List Cycle II
2014-04-04 23:48
441 查看
Problem link:
http://oj.leetcode.com/problems/linked-list-cycle-ii/
The solution has two step:
Detecting the loop using faster/slower pointers.
Finding the begining of the loop. After two pointers meet in step 1, keep one pointer and set anther to the head. Let the two pointers both go one step for each iteration. The iteration terminates when two pointers meet, then the position of the two pointers is the begining node of the loop.
The correctness proof could be found in my homepage doc.
The python code for this problem is as follows.
http://oj.leetcode.com/problems/linked-list-cycle-ii/
The solution has two step:
Detecting the loop using faster/slower pointers.
Finding the begining of the loop. After two pointers meet in step 1, keep one pointer and set anther to the head. Let the two pointers both go one step for each iteration. The iteration terminates when two pointers meet, then the position of the two pointers is the begining node of the loop.
The correctness proof could be found in my homepage doc.
The python code for this problem is as follows.
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a list node def detectCycle(self, head): # Detect the loop p1 = head p2 = head while p2 is not None: p1 = p1.next if p2.next is None: # No loop return None p2 = p2.next.next if p1 == p2: break # have a loop if p2 is None: return None # Find the start of the loop p1 = head while p1 != p2: p1 = p1.next p2 = p2.next return p1
相关文章推荐
- LeetCode OJ-- Linked List Cycle II **
- LeetCode OJ:Linked List Cycle II
- LeetCode OJ - Linked List Cycle II
- LeetCode OJ:Linked List Cycle II(循环链表II)
- Linked List Cycle II
- [leet code] Linked List Cycle II
- [刷题]Linked List Cycle II
- Linked List Cycle II
- LeetCode OJ--Reverse Linked List II
- LeetCode142:Linked List Cycle II
- [leetcode142]Linked List Cycle II
- LeetCode: Linked List Cycle II [142]
- linked-list-cycle-ii
- Linked List Cycle II
- leecode 解题总结:142. Linked List Cycle II
- leetcode 10 Linked List Cycle II
- LeetCode刷题(C++)——Linked List Cycle II(Medium)
- Linked List Cycle I,II, Partition List
- [LeetCode] Linked List Cycle II
- Linked List Cycle II