这是leetcode第141题-环形链表。题目是:给你一个链表的头节点 head ,判断链表中是否有环。
我的问题是:下面代码中的 while head什么时候终止?head作为一个节点类,其只有val和next,那么while到底是判断哪个?
# 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:
seen = set()
while head:
if head in seen:
return True
seen.add(head)
head = head.next
return False
#作者:力扣官方题解
#链接:https://leetcode.cn/problems/linked-list-cycle/solutions/440042/huan-xing-lian-biao-by-leetcode-solution/
#来源:力扣(LeetCode)
#著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。