leetcode 【 Linked List Cycle 】 python 实现
题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
代码:oj在线测试通过 Runtime: 416 ms
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 # @param head, a ListNode 9 # @return a boolean 10 def hasCycle(self, head): 11 if head is None or head.next is None: 12 return False 13 14 p1 = ListNode(0) 15 p1.next = head 16 p2 = ListNode(0) 17 p2.next = head 18 19 result = False 20 while p1 is not None and p2 is not None: 21 if p1 == p2: 22 result = True 23 break 24 else: 25 p1 = p1.next 26 p2 = p2.next 27 if p2 is not None: 28 p2 = p2.next 29 30 return result
思路:
这是一道经典的题 关键点是快慢指针
p1是慢指针,一次走一步;p2是快指针,一次走两步;如果有循环,则快慢指针一定会在某一时刻遇上。
有个问题比较关键:为啥进入循环后,快指针一定能在某一时刻跟慢指针踩在同一个点儿上呢?
小白觉得可以如下解释:
假设现在快慢指针都在循环当中了,由于循环是个圈,则可以做如下的等价:“慢指针一次走一步,快指针一次走两步” 等价于 “慢指针原地不动,快指针一次走一步”这个其实跟物理学中的相对运动原理差不多。
欢迎高手来拍砖指导。