力扣的环形链表解法
题目描述:
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 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
解释:链表中没有环。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
参考程序1:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next or not head.next.next:
return False
F = S = head
while(F.next.next and S.next):
F = F.next.next
S = S.next
if not F.next or not S.next: #加if避免NoneType
return False
if F == S:
return True
return False
运行结果1:
参考程序2:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False
visitline = set()
while(head):
if head in visitline:
return True
else:
visitline.add(head)
head = head.next
return False
运行结果2:
参考程序3:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
line1=line2=head#line1每次跑1步,line2每次跑2步
while line2.next and line2.next.next:#判断跑得快的是否为空
line1=line1.next
line2=line2.next.next
if line1==line2:#存在环则一定会出现相等
return True
return False
运行结果3: