题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # # @param head ListNode类 # @return bool布尔型 # class Solution: def hasCycle(self , head: ListNode) -> bool: if head is None: return False if head.next is None: return False while head.next: if head.val == 100001: return True head.val = 100001 head = head.next return False
骚操作,已知数据小于100001 ,用 100001 做标记缺点,修改了链表的值,违反数据安全性,实际应用中为了保证数据安全,需要深copy链表,违反空间复杂性要求。运行时间:71ms超过70.46% 用Python 3提交的代码占用内存:7892KB超过14.28%用Python 3提交的代码