给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出: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
"""
cur = head
link_list = []
link_list.append(head)
while cur:
#遍历链表,当链表中的节点没有出现过的时候 添加在列表中,如果出现过就说明有环,则返回True。当cur为空时结束循环,也就是说明该链表是非循环的,返回False。
cur = cur.next
if cur in link_list:
return True
else:
link_list.append(cur)
return False
执行用时 : 1728 ms, 在Linked List Cycle的Python提交中击败了6.28% 的用户
内存消耗 : 17.9 MB, 在Linked List Cycle的Python提交中击败了38.82% 的用户
改进方案:利用循环链表的特点,在利用指针遍历的过程中,使用两个指针,一个快的,一个慢的,如果两个指针在遍历过程中有重合的情况,这就说明一定是有环存在的,返回True。如果没有环存在的话,在遍历过程中会报错,因为链表最后一个节点的next为None,此时如果再继续next的话会报错,所以这个时候可以加入try-except,当报错的时候就说明链表无环,返回False。此外当cur_fast为空的时候也返回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
"""
cur_slow,cur_fast = head,head
while cur_fast and cur_fast.next:
cur_slow,cur_fast = cur_slow.next,cur_fast.next.next
if cur_slow == cur_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
"""
cur_slow = head
cur_fast = head
while cur_fast:
try:
cur_slow = cur_slow.next
cur_fast = cur_fast.next.next
if cur_slow == cur_fast:
return True
except Exception as e:
return False
return False
执行用时 : 60 ms, 在Linked List Cycle的Python提交中击败了97.59% 的用户
内存消耗 : 18.1 MB, 在Linked List Cycle的Python提交中击败了23.15% 的用户