Description
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?
这题回忆满满呀。当初进实验室前,道佳面试我的时候就问了这题。当时临时想的就是最蠢的标记法,或者开数组存储遍历过的节点之类的…显然在不能修改链表和不知道链表有多长的时候,这种做法是不实际的。当时道佳就跟我说了快慢指针的做法,后来也和小嘎嘎讨论过这题,有次还仔细的思考了为啥俩指针速度要差一倍,可惜现在都忘了当初的思考结果了。
Code
# 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
"""
slow = fast = head
while slow != None and fast != None:
slow = slow.next
fast = fast.next
if fast == None:
return None
else:
fast = fast.next
if fast == slow:
break
if fast == None:
return None
while head != fast:
head = head.next
fast = fast.next
return head
Conclusion
网上的解释很多,随便一搜就有,此处只记录个算法。