0141-leetcode演算法實現之環形連結串列-linked-list-cycle-python&golang實現
阿新 • • 發佈:2021-11-04
給定一個連結串列,判斷連結串列中是否有環。
如果連結串列中有某個節點,可以通過連續跟蹤 next 指標再次到達,則連結串列中存在環。 為了表示給定連結串列中的環,我們使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該連結串列中沒有環。注意:pos 不作為引數進行傳遞,僅僅是為了標識連結串列的實際情況。
如果連結串列中存在環,則返回 true 。 否則,返回 false 。
進階:
你能用 O(1)(即,常量)記憶體解決此問題嗎?
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:連結串列中有一個環,其尾部連線到第二個節點。
示例2:
輸入:head = [1,2], pos = 0
輸出:true
解釋:連結串列中有一個環,其尾部連線到第一個節點。
示例 3:
輸入:head = [1], pos = -1
輸出:false
解釋:連結串列中沒有環。
提示:
連結串列中節點的數目範圍是 [0, 104]
-105 <= Node.val <= 105
pos 為 -1 或者連結串列中的一個 有效索引 。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/linked-list-cycle
python
# 141.環形連結串列 class ListNode: def __init__(self, val): self.val = val self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: """ 雙指標, 快慢指標, 時間O(n), 空間O(1) 思路: - 初始化slow,fast快慢指標 - fast走2步,slow走1步 - 有環時,fast一定會和slow相遇 - 無環時,fast一定先走到None :param head: :return: """ slow, fast = head while fast != None: fast = fast.next if fast != None: fast = fast.next if fast == slow: return True slow = slow.next return False
golang
// 雙指標之快慢指標,有環必相交
func hasCycle(head *ListNode) bool {
slow, fast := head, head
for fast != nil {
fast = fast.Next
if fast != nil {
fast = fast.Next
}
if fast == slow {
return true
}
slow = slow.Next
}
return false
}