Creating a very simple Singly Circular List C#

天大地大妈咪最大 提交于 2019-12-11 01:05:35

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/5518395/creating-a-very-simple-singly-circular-list-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!