βœ… I don't understand what I did wrong(list)

a list is a circle if its last node points at a previous node. I tried writing a function that can tell whether a given list is a circle, it works except for the last 3 check ups where it loops forever. I provided pics of my code and the running code. *ListFromString points the last node of a given list of int at the first one) *I only had problems with the code inside the for loop
No description
No description
6 Replies
𝓭𝓾𝓼𝓴𝔂 🐸
I believe the problem must be caused by the circle part of the list repeating itself over and over but curr1 and curr2 should meet and I checked it on paper and it seemed to work so I'm not sure what the problem is
Kouhai
Kouhaiβ€’11mo ago
a list is a circle if its last node points at a previous node. Do you mean if it's last node points at the first node? Or just if it points at any previous node?
𝓭𝓾𝓼𝓴𝔂 🐸
any previous one in the for loop it'd be 1->0 -> 0 ->... and it's still considered a circle
Kouhai
Kouhaiβ€’11mo ago
You can use Floyd's cycle-finding algorithm, it would be something like
var n1 = node1;
var n2 = node1;
while(n1 != null && n1.Next != null)
{
n2 = n2.Next;
n1 = n1.Next.Next;
if(n1 == n2)
{
return true;
}
}
return false;
var n1 = node1;
var n2 = node1;
while(n1 != null && n1.Next != null)
{
n2 = n2.Next;
n1 = n1.Next.Next;
if(n1 == n2)
{
return true;
}
}
return false;
Kouhai
Kouhaiβ€’11mo ago
The idea behind the algorithim is that n1 moves faster So for example 0 -> 1 -> 3 -> 1 ^ n1 n2 1 iteration 0 -> 1 -> 3 -> 1 ^ ^ n2 n1 2 iteration 0 -> 1 -> 3 -> 1 ^ ^
n1 n2
3 iteration 0 -> 1 -> 3 -> 1 ^ ^ n1 n2 4 iteration 0 -> 1 -> 3 -> 1 ^ n1 n2 Means it's a full cycle
Want results from more Discord servers?
Add your server