3

我写了一个创建链表副本的方法。
你们能想出比这更好的方法吗?

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;

        }
4

4 回答 4

10

您可以一次性完成,如下所示:

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;

    }
于 2009-07-18T23:49:08.827 回答
5

@Greg,我把你的代码写得更短了:)

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();
     Node current = first;

     do
     {
         // Copy the data of the Node
         current.Data = n.Data;
         current = (current.Next = new Node());
         n = n.Next;
     } while (n != null)

     return first;    
}

Do-While 结构经常被遗忘,但在这里很合适。
Node.Clone() 方法也很好。

+1 给 Greg 一个很好的例子。

于 2009-07-19T00:30:21.360 回答
2

中小型列表的递归方法。

public static Node Duplicate(Node n)
{
    if (n == null)
        return null;

    return new Node() {
        Data = n.Data,
        Next = Duplicate(n.Next)
    };
}
于 2009-07-19T00:05:03.757 回答
0

如果我错过了什么,我很抱歉,但是有什么问题

LinkedList<MyType> clone = new LinkedList<MyType>(originalLinkedList);

LinkedList 构造函数上的 .NET API

于 2019-12-10T17:14:12.523 回答