views:

80

answers:

1

Since long back I have not used C or C++ ,so forget completely about Pointers. I'm familiar with C# and have written a basic version of this. Need to know whether I'm doing right/wrong?

Input:Linked List a->b->c->d->e->null

Output: Linked List b->a->d->c->e->null

We have to write code such that memory position is swapped and not the node value.

    public void SwapLinkedList(LinkedList<int> LL)
    {
        LinkedListNode<int> current = LL.First;
        while (current.Next != null)
        {
            int temp = current.Next.Value;
            current.Next.Value = current.Value;
            current.Value = temp;
            current = current.Next.Next;
        }
    }
+1  A: 

The LinkedListNode order within a LinkedList can't be changed cause the LinkedListNode only allows a get on the Previous and Next properties. So to change the ordering within a LinkedList you can only swap the values (which allow a set).

So to get this to work, i would use some extension methods like these to make the swapping a little more general:

public static class LinkedListExtensions
{
    public static LinkedList<T> SwapPairwise<T>(this LinkedList<T> source)
    {
        if (source == null)
            throw new ArgumentNullException("source");

        var current = source.First;

        if (current == null)
            return source;

        while (current.Next != null)
        {
            current.SwapWith(current.Next);
            current = current.Next;

            if (current != null)
                current = current.Next;
        }

        return source;
    }

    public static void SwapWith<T>(this LinkedListNode<T> first, LinkedListNode<T> second)
    {
        if (first == null)
            throw new ArgumentNullException("first");

        if (second == null)
            throw new ArgumentNullException("second");

        var tmp = first.Value;
        first.Value = second.Value;
        second.Value = tmp;
    }
}
Oliver