题目链接
https://leetcode-cn.com/problems/linked-list-cycle/
题目描述
代码初步
- 思路:运用hash_table将当前节点放在哈希表中,如果后面遍历链表与哈希表的key作比较,存在则存在闭链。
# 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
"""
hash_table = {}
while head!=None:
if head in hash_table:
return True
else:
hash_table[head]=1
head=head.next
return False
代码欣赏
- 思路来自leetcode官方题解:
想象一下,两名运动员以不同的速度在环形赛道上跑步会发生什么?
1.如果列表中不存在环,最终快指针将会最先到达尾部,此时我们可以返回 false
2.列表中存在环形链表,把慢指针和快指针想象成两个在环形赛道上跑步的运动员(分别称之为慢跑者与快跑者)。而快跑者最终一定会追上慢跑者
# 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
"""
if head==None:
return False
slow= head
fast=head.next
while(slow!=fast):
if(fast==None or fast.next==None):
return False
else:
slow=slow.next
fast=fast.next.next
return True