141. 环形链表

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func hasCycle(head *ListNode) bool {
  
    listMap := map[*ListNode]struct{}{}
    for head != nil {
        if _, ok := listMap[head]; ok {
            return true
        }
        listMap[head] = struct{}{}
        head = head.Next
    }
    return false
}

func hasCycle2(head *ListNode) bool {
    if head == nil || head.Next == nil {
        return false
    }

    slow := head
    fast := head.Next

    // 快慢指针相遇,说明有环
    for slow != fast {
        if fast == nil || fast.Next == nil {
            return false
        }

        slow = slow.Next
        fast = fast.Next.Next // 快指针走两步
    }
    return true
}
posted @ 2024-06-07 15:56  gdut17_2  阅读(16)  评论(0)    收藏  举报