Need help with question about lists
We say that a list "contains a circle" if there is a link in it that points to the link that appeared before it
in the list.
For example the following list contains a circle:
Write an action called HasCircle that receives a list of integers.
The operation will return an answer as to whether the received list contains a circle.
31 Replies
what does your code look like so far?
public static bool HasCircle(Node<int> lst)
{
Node<int> curr = lst;
if(curr == null)
return false;
if (CircleSize(lst) == 1 && curr.GetNext() == lst)
return true;
if (CircleSize(lst) == 1 && !curr.HasNext())
return false;
bool flag = false;
Node<int> temp = lst.GetNext();
while(curr != null && !flag)
{
while(temp != null && !flag)
{
if (temp.GetNext() == curr)
flag = true;
temp = temp.GetNext();
}
curr = curr.GetNext();
temp = curr.GetNext();
if (curr.HasNext())
temp = temp.GetNext();
else
curr = curr.GetNext();
}
return flag;
}
$code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
For longer snippets, use: https://paste.mod.gg/sry i dont know what to do
yall have an idea pls?
so the goal is just to detect a cycle in a linked list?
yes
this is an example i was given
?
what do you think you'd need to detect if that happened?
wdym?
i need to return true if it has an inner circled list
yes, so what do you think would be useful to help you find that out?
i was thinking going over the list checking every cell to check if its connected to the first then the second, third and so on
sry i took time to respond
ty for helping
sounds like something that could work, did you try it?
yes
i have trouble with writing the code itself bc lists is pretty new to me
to clarify, this isn't something a C# programmer would call a "list"
we have an actual List<T> type, this would be referred to as a linked list
oh really
oh
so a node?
a linked list
ok
sry mb
a linked list is a collection of nodes where each node contains a value and a reference to the next node
(which is what you have)
yes this is what i meant
english is not my first language so my translation is poor
np, just wanted to avoid any confusion
ok i understand now
so where do i start to check that there is a circled linked list inside a linked list?
maybe i just overcomplicated the code but idk how to put what i think into the code
the nested loops solution you suggested sounds like something that would work
so you'd loop over every node in your list, then inside that loop check every node up to the current node and see if your "current" node points to it
can it pointto itself?
does it matter?
that's up to your project's requirements
i would consider a node pointing to itself to be a cycle personally
yeah i think it is
does it affect the code?
it would, yes
it would change where you stop checking in your inner loop
ok ill try
i changed it abit and it doesnt work in a case that its in the middle or after