题解 | #牛牛队列成环#
牛牛队列成环
https://www.nowcoder.com/practice/38467f349b3a4db595f58d43fe64fcc7
- 题目考察的知识点: 判断链表是否有环
- 题目解答方法的文字分析
- 定义两个指针变量 slow 和 fast,初始都指向头节点 head
- 每轮循环中,slow 指针走一步,fast 指针走两步
- 如果 fast 能够追上 slow, 对应到题目里面要写出fast.val == slow.val(因为值唯一), 说说明链表有环,返回 true
- 如果循环遍历结束后 fast 未能追上 slow,说明链表无环,返回 false
- 本题解析所用的编程语言: Python
- 完整且正确的编程代码
# 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 not head or not head.next:
return False
slow = head
fast = head.next
while slow.val != fast.val:
if not fast or not fast.next:
return False
print(slow.val, fast.val)
slow = slow.next
fast = fast.next.next
return True
牛客高频top202题解系列 文章被收录于专栏
记录刷牛客高频202题的解法思路
查看13道真题和解析