2010-08-13 4 views
0

오래 전부터 C 나 C++를 사용하지 않았으므로 포인터에 대해서는 완전히 잊어 버렸습니다. 저는 C#에 익숙하며 이에 대한 기본 버전을 작성했습니다. 내가 옳고 그른대로하고 있는지 알아야합니까?하나의 링크 된 목록에서 노드 교환하기

입력 : 링크 된 목록 A-> B-> C-> D-> 전자> 널

출력 : 링크 된 목록 B-> A-> D -> C -> 전자> 널

우리는 메모리 위치가 교체되고 노드 값이 아닌 코드를 작성해야합니다. LinkedListLinkedListNode 순서가 LinkedListNode 원인 변경할 수 없습니다

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

'교환'을 정의하십시오. 이 코드는 첫 번째 목록 값을 올바르게 끝냅니다. 원하는 값입니까? –

+0

이 글을 살펴보세요 http://stackoverflow.com/questions/1535988/swapping-nodes-on-a-single-linked-list – Alam

답변

4

만이 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; 
} 
관련 문제