1. 题目
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
2. 优答
如果在链表没走完的情况下,找到完全相同的节点,就是找到环了。
当链表存在环时,就不能这么重构__repr__函数了。
class ListNode: def __init__(self, x): self.val = x self.next = None # def __repr__(self): # # def __str__(self): # if self is None: # return "Nil" # else: # return "{} -> {}".format(self.val, repr(self.next)) class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ if not head: return False fast = slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if fast == slow: return True return False solution = Solution() head = ListNode(0) head.next = ListNode(1) head.next.next = ListNode(2) head.next.next.next = head.next print(head) s = solution.hasCycle(head) print(s)