您的位置:首页 > 编程语言 > Python开发

leetcode 【 Linked List Cycle II 】 python 实现

2015-01-03 15:58 453 查看
公司和学校事情比较多,隔了好几天没刷题,今天继续刷起来

题目

Given a linked list, return the node where the cycle begins. If there is no cycle, return
null
.

Follow up:
Can you solve it without using extra space?

代码:oj 测试通过 Runtime: 596 ms

# 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):
if head is None or head.next is None:
return None

dummyhead = ListNode(0)
dummyhead.next = head

p1 = ListNode(0)
p1.next = head
p2 = ListNode(0)
p2.next = head

first_meet = None
while p1 is not None and p2 is not None:
if p1 == p2:
first_meet = p1
break
else:
p1 = p1.next
p2 = p2.next
if p2 is not None:
p2 = p2.next

result = None
if first_meet is None:
return None
else:
p2 = dummyhead
while p1 is not None and p2 is not None:
if p1.next == p2.next:
result = p1.next
break
else:
p1 = p1.next
p2 = p2.next
return result


思路

主要利用快慢指针的思想。

自己没太多思路,直接参考下面几篇靠谱的日志:
http://www.cnblogs.com/hiddenfox/p/3408931.html http://blog.csdn.net/cs_guoxiaozhu/article/details/14209743
如果链表中没有循环自不必说;

如果有循环:

快慢指针第一次相遇之后,把一个指针重新指向head,然后两个指针相同速度往前走;

两个指针第二次相遇的位置就是循环开始的位置

Tips:

自己在实现的时候犯了一个错误,迭代p1 p2 找到二次相遇的位置 直接返回p1,这里迷糊了:应该迭代p1 p2判断p1.next与p2.next相等,再返回p1.next;这样返回的点才是原来链表中的,而不是构造出来的p1。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: