Does anyone have an example of a very simple implementation of a Circular Linked list using C#?
I have this linked list but i dont know how to makeit cicular:
public class LinkedList
{
public class Node
{
public Node next;
public Object data;
}
private Node head;
public void Add(Object data)
{
Node toAdd = new Node();
toAdd.data = data;
Node current = head;
current.next = toAdd;
}
}
Thanks.
For your linked list to be circular, your tail node should reference the head node. So it's just a matter of doing this at the end of your Add()
method:
toAdd.next = head;
Do note that your Add()
method doesn't iterate through all the nodes in your linked list, it simply does
Node current = head;
So if you try to add multiple nodes, only the head node will be updated to point to each new one, replacing whatever reference it had in each Add()
call, and your linked list will always only contain 2 nodes at most.
You can iterate through every node like this (this replaces the line I mention above):
Node current = head;
while (current.next != head)
{
current = current.next;
}
Now current
will represent your tail node no matter how many nodes you add to your linked list. Then you can append the new tail node, make the old one point to the new one, and the new one point back to your head node.
Another thing: your current implementation of Add()
requires that you initialize your linked list with a head node, otherwise a NullReferenceException
will be raised if you try to add anything. You can write a constructor to handle this issue easily.