How to delete a loop in one linked list?

I'm not sure how to find the start of a loop without using O (N) memory and flags

+3
source share
5 answers
  • Locate the node inside the loop (see the "Response to 1800" section for details). Let me call it node C
  • Find the length of the loop by moving the pointer from C until it reaches again C. The length of the loop is the number of steps that were taken. Let me call this length L
  • Create a pointer that L moves forward from the start point and the other points to the start. Now push them one step at a time until they are gathered. This will be the entry point to the loop.

Time O (N), O (1).

btw, why do you need this?

+6
source

, , O (n) . . , - , .

+3

, , node (, ) "" node, , node "" (, node ).

1800 , node . , , ( , ), node .

+2

, yairchu 1800 - - , , ; -)

, , 4 .

a- > b- > c β†’ ...

a , ( , ) , , , . Woo woo! , , .

, , a, , . ( , , .)

, , , node b , . , , a b, a node . , , b node , , .., . , , .

O (n ^ 2), , .

+1

, node, , , .

-1

Source: https://habr.com/ru/post/1715289/


All Articles