给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
快慢指针法,如果有环,总会相遇
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow, fast = head, head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
每经过一个节点,都卷回头指针,因此如果有环,必会碰到头指针
循环次数比上一个少
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
curr = head
while curr is not None:
nextnode = curr.next
if nextnode is head:
return True
curr.next = head
curr = nextnode
return False