文章目录
题目要求
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
说明:不允许修改给定的链表。
进阶:
你是否可以使用 O(1) 空间解决此题
解题思路
方法一:字典(哈希表)
# 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
"""
dic = {
}
while head:
if head in dic:
return head
dic[head] = 1
head = head.next
return head
方法二:快慢指针
空间复杂度为O(1)
# 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
"""
fast = head
slow = head
# 快慢指针第一次相遇,快指针每次前进2,慢指针每次前进1
while fast is not None:
slow = slow.next
fast = fast.next
if fast is not None:
fast = fast.next
if fast == slow:
break
# 如果快指针为None,证明无环,返回None
if fast == None:
return None
# 此时重新设置一指针ptr为head,或直接利用fast指针(因为之后不用原先的fast指针了),每次跟慢指针一样前进1
fast = head
while fast != slow:
slow = slow.next
fast = fast.next
return fast