2010-08-13 76 views
0

自从我早已没有使用C或C++,所以完全忘记了Pointers。我熟悉C#并且已经写了一个基本版本。需要知道我是否正确/错误?在单个链表上交换节点

输入:链表A-> B-> C-> D-> E->空

输出:链表B-> A-> D-> C-> E->空

我们必须编写代码,以便交换内存位置,而不是节点值。

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

定义“交换”。这段代码将第一个列表值正确地放在最后,它是你想要它做什么的? – 2010-08-13 04:00:39

+0

看看这个帖子 http://stackoverflow.com/questions/1535988/swapping-nodes-on-a-single-linked-list – Alam 2010-08-13 04:07:54

回答

4

一个LinkedList内的LinkedListNode顺序不会引起LinkedListNode改变只允许在PreviousNext性能得到。因此,要更改LinkedList内的排序,您只能交换值(允许设置)。

因此,要得到这个工作,我会用一些扩展方法,如这些使交换多一点一般:

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

如果你有一个LinkedListNode参考首选删除和添加:

public static LinkedListNode<T> SwapWith<T>(LinkedListNode<T> first, LinkedListNode<T> second) 
{ 
     first.List.Remove(first); 
     second.List.AddAfter(second, first); 
     return second; 
}