您的位置:首页 > 其它

Leetcode #142 Linked List Cycle II

2015-09-10 09:51 288 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.

Note: Do not modify the linked list.

Follow up:

Can you solve it without using extra space?

Difficulty: Medium

如果不用额外的space,这里有一个小技巧。

假设我们在第一次p = pNext时,p走了N步,pNext走了2N步,两个指针的步数之差正好就是一个cycle的步数,也就是2N-N = N。

设进入这个循环需要X步,那么此时指针p和pNext离cycle的起点正好差X步(可以画个图想想)。所以,让p回到head,同时开始走,每次都只走一步,下一次相遇就是cycle的入口。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
flag = 0
p = head
pNext=head

while (p is not None) and (pNext is not None) and flag==0:
if p.next is None or pNext.next is None:
return None
p = p.next
pNext = pNext.next.next
if p==pNext:
flag = 1
if flag == 0:
return None
p = head;
while p!=pNext:
p = p.next
pNext = pNext.next
return p
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: