#判断单链表是否有环(如1->2->3->4->5->3有环,环的入口为3)
#特殊情况:链表为空,长度为1时,都不是有环链表
#方法1:(将结点遍历加入列表,若列表中某个结点已经存在,说明该结点有两个,即链表有环)
class Solution:
def hasCycle(self,head):
visited=[]
while head!=None:
if head in visited:
return True
visited.append(head)
head=head.next
return False
#方法2:(快慢指针遍历法)
class Solution:
def hasCycle(self , head ):
if head is None or head.next is None:
return False
slow=head #初始化low指针指向头结点
fast=head.next #初始化fast指针指向次结点
while slow!=fast:
if fast is None or fast.next is None:#若无环,fast遍历到最后结点位置时,fast.next为空
return False
slow=slow.next #low指针每次只走一步
fast=fast.next.next #fast指针每次走两步
return True