演算法:環形連結串列
阿新 • • 發佈:2021-01-07
技術標籤:資料結構與演算法
題目:判斷連結串列是否有環
//環形連結串列 //雜湊表 func hasCycle(head *ListNode) bool { seen := map[*ListNode]struct{}{} for head != nil { if _, ok := seen[head]; ok { return true } //標記該節點已被訪問 seen[head] = struct{}{} head = head.Next } return false } //快慢指標 func hasCycle(head *ListNode) bool { if head == nil || head.Next == nil { return false } slow, fast := head, head.Next for fast != slow { if fast == nil || fast.Next == nil { return false } //慢指標一次移動2步 slow = slow.Next //快指標一次移動2步 fast = fast.Next.Next } return true }
連結:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode-solution/