• 2 weeks ago
Transcript
00:00I am going to create a function in my linkless class.
00:03Public static boolean is cycle.
00:09In fact, I will not keep static here.
00:12I will create this cycle.
00:14First of all, we will define a slow pointer
00:17which will start with head.
00:19Then we will define a fast pointer
00:20which will start with head.
00:22Now I have to run a loop.
00:24Until I am, fast is not equal to null.
00:27And until my next is not equal to null.
00:32Now I know that this condition is my condition
00:35which is a normal linkless without cycle.
00:38What will I do every time?
00:40I will create slow.
00:41So this is my move.
00:43And I have created fast next.
00:48So this is my move.
00:50I will check that if the value of slow
00:53is equal to fast.
00:54In this case, I know that I have to return true.
00:58That means that the cycle exists.
01:01If it doesn't happen,
01:02I will return false.
01:04False return means that the cycle doesn't exist.
01:11Let's do this and save.
01:12What will I do in the main function?
01:15I am going to initialize my head with a new node.
01:19One.
01:20Now I will initialize the next head with a new node.
01:25You can also do it in your own code.
01:27Or if we are going to perform this cycle
01:31or if we are going to perform this cycle
01:32in a new coding test,
01:32I have to write this cycle in a coding test.
01:35Then I don't need to create a linkless.
01:37Otherwise, I am creating a main function in the main function.
01:39I am doing cycle in which the cycle exists.
01:41So I have to point 2 to head next to head next to next.
01:46I have to point 3 to head next to next to next.
01:54It is next. It is also next.
01:56It is pointing to my head.
01:59I have made a loop in this way.
02:02I have pointed to 1 to 2.
02:04I have pointed to 2 to 3.
02:063 is pointing to my head or not to 1.
02:09So, there exists a cycle in my linked list.
02:11So, I will call my head.is.
02:16Or, if I make static type,
02:22I will call this cycle.
02:25Let's save this cycle.
02:26And now run.
02:30So, I have returned to true.
02:33And if I remove the last line,
02:34I will remove this cycle from 1.
02:37In this case, I should print it false.
02:40So, this time it is false.
02:41So, in this way, we detect a cycle in our linked list.
02:46Now, the whole process,
02:47which we have found out,
02:49I know the name of Floyd's Cycle Finding Algorithms.
02:54And you can remember this name.
02:56In fact, it is not necessary to remember.
02:58Just use a little logic.
03:00How can we use slow fast?
03:01How can we use fast?
03:02When fast comes to null or last node.
03:06But in the cycle,
03:07there is no last node or null.
03:10So, in this case,
03:10it will never be reached.
03:12So, in this case,
03:13I will return to true.
03:15Google.