2016-04-26 7 views
0

ノードベースのリストにノードを追加するために 'Add(int n)'メソッドを作成しようとしています。リストがソートされているので、適切な場所にノードを追加したいので、ノードを追加した後もソートされます。c#ソート済みノードベースのリストに値を追加する

例:

カレントノードリストの値:1 - 2 - 2 - 3 - 追加する5 値:2 結果:1 - 2 - - 2 - 2 - 5

私が作っnodelistと 私のコード:というクラス

とき「n」のノードベースのリストの最初の要素を把握するのは簡単だったが、私はどれだけに把握するように見える傾けるよりも小さくなっているノードを追加
class NodeList 
    { 
     private int head; 
     private NodeList tail; 

     public NodeList(int head, NodeList tail) 
     { 
      this.head = head; 
      this.tail = tail; 
     } 

     public NodeList Add(int n) 
     { 
      NodeList nl = new NodeList(head, tail); 
      NodeList result = null; 
      if (nl.head > n) 
       result = new NodeList(n, nl); 
      else 
      { 
       //cant figure this part out 
      } 
      return result; 
     } 
    } 

そうでない場合はそれをしてください。

追加情報:

リストには重複を含めることができます。 NodeListクラスは、iが含むものより多くのインスタンス変数を持っていません。

+0

リストを使用してみてください。ユーザーがAdd(int n)を呼び出すたびに、値を追加してソートします。 –

答えて

1

あなたはこの不変を維持したいと常に新しいインスタンスを作成したいと仮定すると、それ以外の部分は、これを持つことができます

  nl.tail = nl.tail == null ? new NodeList(n, null) : nl.tail.Add(n); 
      return nl; 
+0

彼はリストをソートしたい。 – Linvi

+0

リストがソートされます。 Addがtailで呼び出されると、checkは再帰的に実行され、置き換えられる正しいtailに到達します。 –

+0

これは素晴らしく、実際には私が必要とするものです。なぜなら、プライベートとパブリックの両方の方法を持つ必要があるからです。ありがとう! – FrankK

1

実際に構造体を使用する場合は、次のコードを使用できます。再帰関数を使用して、さまざまな要素を正しいノードまで反復処理します。

public class NodeList 
{ 
    public int Head { get; } 
    public NodeList Tail { get; set; } 

    public NodeList(int head, NodeList tail) 
    { 
     Head = head; 
     Tail = tail; 
    } 

    private NodeList Add(int value, NodeList current) 
    { 
     var nextNode = current.Tail; 

     if (nextNode == null) 
     { 
      current.Tail = new NodeList(value, null); 
      return current.Tail; 
     } 

     if (nextNode.Head > value) 
     { 
      current.Tail = new NodeList(value, nextNode); 
      return current.Tail; 
     } 

     // Recursive 
     return Add(value, nextNode); 
    } 

    public NodeList Add(int value) 
    { 
     if (value < this.Head) 
     { 
      var newRoot = new NodeList(value, this); 
      return newRoot; 
     } 

     Add(value, this); 
     return this; 
    } 
} 
+0

これは、Addメソッドでも1つのパラメータだけで実行できますか? – FrankK

+0

パブリック 'Add'メソッドには1つのパラメータしかありません。 'public NodeList Add(int value)' – Linvi

+0

あなたはそれを望んでいますか? – Linvi