您的位置:首页 > 其它

【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.

# 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: