141. 环形链表

141. 环形链表 #

题目地址 #

解题思路 #

具体实现 #

package main

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func hasCycle(head *ListNode) bool {
	slow, fast := head, head
	for fast != nil && fast.Next != nil {
		slow = slow.Next
		fast = fast.Next.Next
		if slow == fast {
			return true
		}
	}

	return false
}

func main() {
	createLinkedList := func(arr []int) *ListNode {
		if len(arr) == 0 {
			return nil
		}

		head := &ListNode{Val: arr[0]}
		current := head
		for i := 1; i < len(arr); i++ {
			node := &ListNode{Val: arr[i]}
			current.Next = node
			current = node
		}

		// Make it a circular linked list (connect the last node to the head)
		current.Next = head

		return head
	}

	arr := []int{1, 2, 3, 4, 5}
	head := createLinkedList(arr)
	head.Next.Next.Next.Next.Next = head.Next

	// Test the hasCycle function
	if hasCycle(head) {
		fmt.Println("The linked list has a cycle.")
	} else {
		fmt.Println("The linked list does not have a cycle.")
	}
}