问题描述:
给定一个链表,判断链表中是否有环。
思路:用快的指针追慢的指针,只要有圈,一定能追上。
错误:
1 class Solution(object): 2 def hasCycle(self, head): 3 """ 4 :type head: ListNode 5 :rtype: bool 6 """ 7 if head == None or head.next == None: 8 return False 9 p = head.next 10 q = head.next.next 11 while p and q: 12 if p == q: 13 return True 14 p = p.next 15 if q.next != None: 16 q = q.next.next 17 return False
改正:
1 class Solution(object):
2 def hasCycle(self, head):
3 """
4 :type head: ListNode
5 :rtype: bool
6 """
7 if head == None or head.next == None:
8 return False
9 p = head.next
10 q = head.next.next
11 while q and q.next:
12 if p == q:
13 return True
14 p = p.next
15 q = q.next.next
16 return False
2018-09-12 21:03:17