Swapping Nodes on a single linked list
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.Valu开发者_JS百科e = current.Value;
current.Value = temp;
current = current.Next.Next;
}
}
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;
}
}
If you have reference on LinkedListNode prefered remove and add :
public static LinkedListNode<T> SwapWith<T>(LinkedListNode<T> first, LinkedListNode<T> second)
{
first.List.Remove(first);
second.List.AddAfter(second, first);
return second;
}
精彩评论