复制链表

问题描述 投票:3回答:4

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

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;

        }
c# linked-list
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;

    }

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;    
}

While结构通常被遗忘,但非常适合这里。一个Node.Clone()方法也很好。

+ 1为Greg提供了很好的示例。


2
投票

中小型列表的递归方法。

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

    return new Node() {
        Data = n.Data,
        Next = Duplicate(n.Next)
    };
}

0
投票

对不起,如果我错过了什么,但是出了什么问题

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

.NET API on LinkedList Constructors

© www.soinside.com 2019 - 2024. All rights reserved.