怎样才能增加一个链表< T>要在LinkedList< T>在C#中? [英] How does one add a LinkedList<T> to a LinkedList<T> in C#?

查看:106
本文介绍了怎样才能增加一个链表< T>要在LinkedList< T>在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人会认为简单的code

One would think the simple code

llist1.Last.Next = llist2.First;
llist2.First.Previous = llist1.Last;

会的工作,但显然在C#中的链表,首先,最后,和它们的性质只能得到。

would work, however apparently in C#'s LinkedList, First, Last, and their properties are Get only.

另一种方法是我能想到的就是

The other method I could think of was

llist1.AddLast(llist2.First);

不过,这也不行 - 它失败,因为llist2的第一个节点已经在链表

However, this does not work either - it fails because the first node of llist2 is already in a linked list.

这是否意味着,我必须有一个循环,手动llist2的AddLast的每个节点llist1?这难道不是打败链表????效率

Does this mean that I have to have a loop that manually AddLast's each node of llist2 to llist1? Doesn't this defeat the efficiency of linked lists????

推荐答案

是的,你必须循环,很遗憾。这是一个O(n)的操作 - O(1)为每个条目添加。还有的需要一个缓冲的风险调整大小和复制等 - 当然,虽然垃圾收集可能会做粗略的:)你甚至可以写一个方便的扩展方法:

Yes, you have to loop, unfortunately. This is an O(n) operation - O(1) for each entry added. There's no risk of requiring a buffer to be resized and copied, etc - although of course garbage collection might do roughly that :) You could even write handy extension methods:

public static class LinkedListExtensions   
{
    public static void AppendRange<T>(this LinkedList<T> source,
                                      IEnumerable<T> items)
    {
        foreach (T item in items)
        {
            source.AddLast(item);
        }
    }

    public static void PrependRange<T>(this LinkedList<T> source,
                                       IEnumerable<T> items)
    {
        LinkedListNode<T> first = source.First;
        foreach (T item in items)
        {
            source.AddBefore(first, item);
        }
    }
}

编辑:埃里希的意见建议,为什么你可能会认为这是低效的 - 为什么不加入我们的两个列表一起通过更新第一列表的尾部和preV的下一个指针头指针的第二?嗯,想想会发生什么样的第二列表... 的会随之改变。

不仅如此,但会发生什么这些节点的所有权?每个本质上是两个列表的一部分,现在...但一个LinkedListNode&LT; T&GT;的.List 属性只能说服他们约一

Not only that, but what would happen to the ownership of those nodes? Each is essentially part of two lists now... but the LinkedListNode<T>.List property can only talk about one of them.

虽然我能明白你为什么会想这样做在某些情况下,该方式使.NET 的LinkedList&LT; T&GT; 类型已建成基本禁止它。我觉得这个文档注释中解释说得好:

While I can see why you might want to do this in some cases, the way that the .NET LinkedList<T> type has been built basically prohibits it. I think this doc comment explains it best:

的LinkedList&LT; T&GT;)类做   不支持链接,分裂,   周期,或其它功能,可以   离开不一致名单   状态。

The LinkedList<T>) class does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state.

这篇关于怎样才能增加一个链表&LT; T&GT;要在LinkedList&LT; T&GT;在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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