tags:

views:

589

answers:

3

I wrote a method which creates a copy of linked list.
Can you guys think of any method better than this?

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;

        }
+6  A: 

You can do it in one pass, something like 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;

    }
Greg Hewgill
awesome solution...thanks for the help..I think I need to improve a lot in my coding skills ....:)
Learner
I think we need to point the next pointer of last node to null....so after while loop we need to have a statement temp.Next = null
Learner
You're right, if the `Node()` constructor does not do this automatically (I think it should), then you will have to do it explicitly.
Greg Hewgill
+1  A: 

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)
    };
}
James M.
+2  A: 

@Greg, I took your code and made it even 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 often forgotten, but fits well here.
A Node.Clone() method would be nice as well.

+1 to Greg for the nice example.

Zyphrax
+1 nice rearrangement. :)
Greg Hewgill