2009-07-18 5 views
3

リンクリストのコピーを作成するメソッドを作成しました。
皆さんはこれよりも優れた方法はありますか?リンクリストを複製する

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; 

     } 

答えて

10

あなたは、1回のパスでこのような何かにそれを行うことができます。

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; 

    } 
+0

素晴らしい解決策...ありがとうございました。私は私のコーディングスキルを向上させる必要があると思います。:) – Learner

+0

私は最後のノードの次のポインタをNULLにする必要があると思います... .so whileループの後に文temp.Next = nullをつける必要があります – Learner

+1

'Node()'コンストラクタがこれを自動的にしないと(私はそうするべきです)、明示的にそれを行う必要があります。 –

2

小/中リストの再帰的な方法を。

public static Node Duplicate(Node n) 
{ 
    if (n == null) 
     return null; 

    return new Node() { 
     Data = n.Data, 
     Next = Duplicate(n.Next) 
    }; 
} 
5

@グレッグは、私はあなたのコードを取り、それが少しでも短く:)

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

DO-ながら構築物はしばしば忘れて、しかしここによく適合されます。
Node.Clone()メソッドもいいでしょう。

いい例のための+1。

+2

+1素敵な並べ替え。 :) –

関連する問題