创建一个非常简单的单循环列表C# [英] Creating a very simple Singly Circular List C#

查看:196
本文介绍了创建一个非常简单的单循环列表C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有一个使用C#的循环链接列表非常简单的实现的例子?



我有这个链表,但我不知道如何使细节:

  public class LinkedList 
{
public class Node
{
public Node下一个;
public对象数据;
}

私有节点头;

public void Add(Object data)
{
Node toAdd = new Node();
toAdd.data = data;
Node current = head;
current.next = toAdd;
}

}

谢谢。

解决方案

您的链接列表为循环,您的尾节点应引用头节点。所以这只是在你的 Add()方法结束时这样做的一个问题:

 code> toAdd.next = head; 






请注意,您的 Add()方法不会遍历链接列表中的所有节点,它只是

  Node current = head; 

所以如果你尝试添加多个节点,只有头节点被更新为指向每个新的一个,替换每个 Add()调用中的任何引用,您的链接列表将始终只包含2个节点。



您可以遍历这样的每个节点(这取代了我上面提到的行):

 节点current =头; 

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

现在当前将代表您的尾节点,无论您添加到链接列表中有多少个节点。那么你可以附加新的尾部节点,使旧的一点到新的点,并且新的一点回到你的头节点。



另一件事:你目前实现 Add()要求您使用头节点初始化链接列表,否则将引发 NullReferenceException 你尝试添加任何东西。你可以写一个构造函数来处理这个问题。


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.

这篇关于创建一个非常简单的单循环列表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆