cycle

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2026 License: BSD-3-Clause Imports: 1 Imported by: 0

README

NAME

18 - detect cycle in a singly linked list

DESCRIPTION

Problem

Given a singly linked list, report whether it has cycles. Do not use a hash set to keep track of visited nodes.

Example

Input:

1 - 2 - 3 - 4
    ^       |
    |       |
    +-------+

Has cycle from item 4 to item 2

SEE ALSO

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Is

func Is(node *Node) bool

Is reports whether the singly linked list has cycles. It uses fast and slow pointers algorithm instead of a set of visited nodes.

Example
package main

import (
	"fmt"

	"github.com/skhal/lab/iq/18/cycle"
)

func main() {
	head := &cycle.Node{
		Val: 1,
		Next: &cycle.Node{
			Val: 2,
			Next: &cycle.Node{
				Val: 3,
			},
		},
	}
	head.Next.Next = head
	fmt.Println(cycle.Is(head))
}
Output:
true

Types

type Node

type Node struct {
	Val  int
	Next *Node
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL