[ACCEPTED]-Duplicate a linked list-linked-list

Accepted answer
Score: 11

You can do it in one pass, something like 1 this:

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;

    }
Score: 5

@Greg, I took your code and made it even 4 a bit shorter :)

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

The Do-While construct is 3 often forgotten, but fits well here.
A Node.Clone() method 2 would be nice as well.

+1 to Greg for the 1 nice example.

Score: 2

Recursive method for small/medium lists.

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

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

0

Score: 2

I'm sorry if I've missed something, but 1 what's wrong with

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

.NET API on LinkedList Constructors

More Related questions