标签:
如何判断是否有环?设置两个头结点指针,一个走的快,一个走的慢,那么若干步以后,快的指针总会超过慢的指针一圈。(python代码)
1 """ 2 Definition of ListNode 3 class ListNode(object): 4 5 def __init__(self, val, next=None): 6 self.val = val 7 self.next = next 8 """ 9 class Solution: 10 """ 11 @param head: The first node of the linked list. 12 @return: True if it has a cycle, or false 13 """ 14 def hasCycle(self, head): 15 # write your code here 16 slow=head 17 fast=head 18 while fast!=None and fast.next!=None: 19 slow=slow.next 20 fast=fast.next.next 21 if slow==fast: 22 break 23 if fast==None or fast.next==None: 24 return False 25 else: 26 return True
标签:
原文地址:http://www.cnblogs.com/suiyuanjianke/p/5346128.html