【LeetCode OJ】Linked List Cycle II

Posted on 2014-04-04 23:48  卢泽尔  阅读(181)  评论(0)    收藏  举报

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.

# 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