Leecode第141题
判断链表是否有环
思路1:破坏链表:把链表内数值域赋一个足够特殊的值,然后当出现这个值证明有环,不出现则无环
代码如下(冒号中间的值就是为了足够特殊。。)
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
while head:
if head.val == 'bjfuvth':
return True
else:
head.val = 'bjfuvth'
head = head.next
return False
思路2:快慢指针法。每一次移动,快指针走两个格,慢指针走一个格。如果快指针先出界,则无环,若快慢指针相遇,则有环。
代码如下*(复杂度为O(n/2))
class Solution:
def hasCycle(self, head: ListNode) -> bool:
'''while head:
if head.val=='haha':
return True
else:
head.val='haha'
head=head.next
return False
'''
if head is None or head.next is None:
return False
slow = head
fast = head.next
while(slow != fast):
if(fast == None or fast.next == None):
return False
slow = slow.next
fast = fast.next.next
return True