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

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

问题描述

什么是建立在C#中循环链表的最佳途径。我应该从链表和LT得到它; T>收藏?我打算用这个链表来存储我的联系人创建一个简单的地址簿(这会是一个吸Y地址簿,但我不在乎,因为我会使用它唯一的一个)。我主要就是想建立关键链接的列表,这样我可以在其他项目中再次使用它。

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一个扩展方法,同样用于检索previous节点或者,如果没有这样的节点存在的最后一个。下面code要做到的是,虽然我没有测试它:

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<object> NextOrFirst(this LinkedListNode<object> current) {
        if (current.Next == null)
            return current.List.First;
        return current.Next;
    }

    public static LinkedListNode<object> PreviousOrLast(this LinkedListNode<object> current) {
        if (current.Previous == null)
            return current.List.Last;
        return current.Previous;
    }
}

现在,你可以叫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天全站免登陆