題意: 給定一個鏈表,返回鏈表開始入環(huán)的第一個節(jié)點。 如果鏈表無環(huán),則返回 null。
為了表示給定鏈表中的環(huán),使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環(huán)。
說明:不允許修改給定的鏈表。
一開始我是這么寫的
# 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
"""
dummy_head = ListNode(next=head)
fast = dummy_head.next.next
slow = dummy_head
len = 0
while fast and slow:
if fast == slow :
return fast
fast = fast.next.next
print(fast.val)
slow = slow.next
print(slow.val)
len += 1
return null
結(jié)果是:
# 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,slow = head,head
# 現(xiàn)在里邊轉(zhuǎn)圈,轉(zhuǎn)到相遇的位置
while True:
if not (fast and fast.next): return
fast,slow = fast.next.next, slow.next
if fast == slow: break
# 再一步一步到相交的位置
fast = head
while fast != slow:
fast,slow = fast.next,slow.next
return fast
這種思路太難想了
看了代碼隨想錄的視頻
文章來源:http://www.zghlxwxcb.cn/news/detail-574087.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-574087.html
到了這里,關(guān)于【Leetcode】142.環(huán)形鏈表II的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!