题目:
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?
依次检查每一个节点。检查的某点的时候,从头开始扫描,看是否能找到一个点,这个点是这个点的next。直到扫描到这个点本身时停止。
* 如果在扫描结束前(即,扫描到这个点本身之前),找到一个点,是这个点的next,这说明我们正在检查的点是链表的尾节点,而我们扫描到的这点正是尾节点循环指回链表指到的那个点。我们需要输出的就是这个点(尾节点)的next
Code1:
class Solution:
# @param head, a ListNode
# @return a list node
def check(self, head, pc):
p = head
while not(p is pc):
if p is pc.next:
return True
p = p.next
if p is pc.next:
return True
else:
return False
def detectCycle(self, head):
if head is None:
return None
pc = head.next
while not(pc is None):
if self.check(head, pc):
return pc.next
pc = pc.next
return None
经检验,这个算法...超时
题解2:
我们解决这个问题的第一个版本,用的是快慢指针的方法。
我们也可以通过这个方法来求借。
我们通过快慢指针能得到的是相遇点,题设给的是头节点。我们要求的是尾节点指回链表的那个节点(称其为目标节点)。
我们现在需要做的就是理清三个节点之间的关系,看图:
我们知道三个点之间的关系之后,代码就很好写了。
两指针相遇之后,将快指针重置指向头结点,慢指针保持指向相遇点。然后两个指针同时开始一步步走,两个指针再次相遇的时候,就是我们所要找的目标节点。
Code2:
class Solution:
def detectCycle(self, head):
if (head is None) or (head.next is None):
return None
p1 = head
p2 = head
while (p2 and p2.next):
p1 = p1.next
p2 = p2.next.next
if (p1 is p2):
break
if (p1 is p2):
p2 = head
while not(p1 is p2):
p1 = p1.next
p2 = p2.next
return p1
return None