Creating a very simple single C # circular list

Does anyone have an example of a very simple implementation of a circular linked list using C #?

I have this linked list, but I don't know how to make it in the form:

    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.

+2
source share
1 answer

For the linked list to be round, your tail node must reference the head of the node. So this is just the question at the end of your method Add():

toAdd.next = head;

Note that your method Add()does not iterate over all nodes of the linked list, it just does

Node current = head;

, , node, , , Add(), 2 .

node ( , ):

Node current = head;

while (current.next != head)
{
    current = current.next;
}

current node , . node, , - node.

: Add() , node, NullReferenceException , - . , .

+6

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


All Articles