C# 复制链接列表
我写了一个创建链表副本的方法。C# 复制链接列表,c#,linked-list,C#,Linked List,我写了一个创建链表副本的方法。 你们能想出比这更好的方法吗 public static Node Duplicate(Node n) { Stack<Node> s = new Stack<Node>(); while (n != null) { Node n2 = new Node(); n2.Data = n.Dat
你们能想出比这更好的方法吗
public static Node Duplicate(Node n)
{
Stack<Node> s = new Stack<Node>();
while (n != null)
{
Node n2 = new Node();
n2.Data = n.Data;
s.Push(n2);
n = n.Next;
}
Node temp = null;
while (s.Count > 0)
{
Node n3 = s.Pop();
n3.Next = temp;
temp = n3;
}
return temp;
}
公共静态节点重复(节点n)
{
堆栈s=新堆栈();
while(n!=null)
{
节点n2=新节点();
n2.数据=n.数据;
s、 推力(n2);
n=n.下一步;
}
节点温度=null;
而(s.计数>0)
{
节点n3=s.Pop();
n3.下一个=温度;
温度=n3;
}
返回温度;
}
您可以一次完成,如下所示:
public static Node Duplicate(Node n)
{
// handle the degenerate case of an empty list
if (n == null) {
return null;
}
// create the head node, keeping it for later return
Node first = new Node();
first.Data = n.Data;
// the 'temp' pointer points to the current "last" node in the new list
Node temp = first;
n = n.Next;
while (n != null)
{
Node n2 = new Node();
n2.Data = n.Data;
// modify the Next pointer of the last node to point to the new last node
temp.Next = n2;
temp = n2;
n = n.Next;
}
return first;
}
中小型列表的递归方法
public static Node Duplicate(Node n)
{
if (n == null)
return null;
return new Node() {
Data = n.Data,
Next = Duplicate(n.Next)
};
}
@格雷格,我把你的代码缩短了一点:) Do-While结构经常被遗忘,但很适合这里。
一个Node.Clone()方法也不错
+我很抱歉,我错过了一些东西,但是你怎么了
LinkedList<MyType> clone = new LinkedList<MyType>(originalLinkedList);
LinkedList clone=新的LinkedList(原始LinkedList);
非常棒的解决方案…感谢您的帮助..我认为我需要在编码技能方面提高很多..:)我认为我们需要将最后一个节点的下一个指针指向null….因此在while循环之后,我们需要一个语句temp.next=null您是对的,如果
node()
构造函数没有自动执行此操作(我认为应该执行此操作),那你就得明确地去做。当然,我的估计也是这样。问题是,除了(正如我所想象的)罕见的情况外,复制链表并不能产生外行可能认为的好处。如果您需要对列表进行不同的排序,或者想要一个经过筛选的副本,但更改副本上的非值对象也会更改原始列表上的非值对象,则这是很好的。这意味着,在尝试此页面上的任何内容之前,您可能需要确保不需要深度拷贝。
LinkedList<MyType> clone = new LinkedList<MyType>(originalLinkedList);