在 C# 中创建循环链表? [英] Creating a circularly linked list in C#?

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

问题描述

在 C# 中创建循环链表的最佳方法是什么.我应该从 LinkedList< 派生它吗?T> 收藏?我打算使用这个链接列表创建一个简单的地址簿来存储我的联系人(这将是一个糟糕的地址簿,但我不在乎,因为我将是唯一使用它的人).我主要是想创建关键链表,以便我可以在其他项目中再次使用它.

What would be the best way to create a circularly linked list in C#. Should I derive it from the LinkedList< T> collection? I'm planning on creating a simple address book using this Linked List to store my contacts (it's gonna be a suck-y address book, but I don't care cause I'll be the only one to use it). I mainly just want to create the crucially linked list so that I can use it again in other projects.

如果您认为链接列表不是正确的方法,请告诉我哪种方法更好.

If you don't think the Linked List is the right way to go let me know which way would be better.

推荐答案

由于这些答案中的大多数实际上并未触及问题的实质,仅触及意图,也许这会有所帮助:

As most of these answers don't actually get at the substance of the question, merely the intention, perhaps this will help:

据我所知,链表和循环链表之间的唯一区别是迭代器到达列表末尾或开头时的行为.支持循环链表行为的一个非常简单的方法是为 LinkedListNode 编写一个扩展方法,该方法返回列表中的下一个节点,如果不存在这样的节点,则返回第一个节点,同样用于检索前一个节点或最后一个节点如果不存在这样的节点,则为一个.下面的代码应该可以实现这一点,虽然我还没有测试过:

As far as I can tell the only difference between a Linked List and a Circular Linked List is the behavior of iterators upon reaching the end or beginning of a list. A very easy way to support the behavior of a Circular Linked List is to write an extension method for a LinkedListNode that returns the next node in the list or the first one if no such node exists, and similarly for retrieving the previous node or the last one if no such node exists. The following code should accomplish that, although I haven't tested it:

static class CircularLinkedList {
    public static LinkedListNode<T> NextOrFirst<T>(this LinkedListNode<T> current)
    {
        return current.Next ?? current.List.First;
    }

    public static LinkedListNode<T> PreviousOrLast<T>(this LinkedListNode<T> current)
    {
        return current.Previous ?? current.List.Last;
    }
}

现在您只需调用 myNode.NextOrFirst() 而不是 myNode.Next,您将拥有循环链表的所有行为.您仍然可以进行恒定时间删除并在列表中的所有节点之前和之后插入等等.如果我遗漏了循环链表的其他一些关键位,请告诉我.

Now you can just call myNode.NextOrFirst() instead of myNode.Next and you will have all the behavior of a circular linked list. You can still do constant time removals and insert before and after all nodes in the list and the like. If there's some other key bit of a circular linked list I am missing, let me know.

这篇关于在 C# 中创建循环链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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