Look at the animation algorithm: ring detection algorithm-Freud's rabbit and tortoise

Introduction

Ring detection should be a very common algorithm problem. How to judge whether there is a ring problem?

A very simple way is to use HashSet to save the data to be traversed. If there is a duplication, you will know that the linked list has a ring. But this method needs to save all the elements traversed, so its space complexity is o(n).

Is there any way to determine whether there is a loop without saving the previous elements?

Take a look at Freud's rabbit and turtle algorithm.

About Freud

Some classmates will say, Freud (Sigmund Freud) who does not know, the author of dream analysis, a famous psychologist, and the founder of the psychoanalytic school.

But the full name of Freud we are talking about here is Robert W. Floyd (Robert Freud) instead of Sigmund Freud.

Robert Freud is a computer scientist, Turing Award winner, the founder of the pre- and post-assertion method, and one of the founders of the heap sort algorithm and the Floyd-Warshall algorithm.

It won the Turing Award in 1978 and is a "self-taught computer scientist".

This rabbit and turtle algorithm is a ring detection algorithm he invented.

Construct a ring

in

Guess you like

Origin blog.csdn.net/superfjj/article/details/108746958