题目
思路
链表无环情况:有空结点
链表有环:有些结点会重复 所以 用集合(哈希表)来记录遍历的结点 结点不存在,则将结点加到集合中,当遍历到的结点存在集合中,即为链表环开始的结点,即有环
代码
# 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 is None:
return False
if head.next is None:
return False
s =set()
p = head
while p:
if p.next is None:
return False
if p in s:
return True
else:
s.add(p)
p=p.next
142. 环形链表 II
思路跟上一题一样,只不过是输出链表环开始的节点
代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
if head.next is None:
return None
s= set()
p = head
while p:
if p.next is None:
return None
if p in s:
return p
s.add(p)
p=p.next