2016-04-26 72 views
0

我試圖使'Add(int n)'方法將節點添加到基於節點的列表。該列表已排序,並且我想將該節點添加到正確的位置,以便在添加節點後仍將對其進行排序。c#將值添加到基於排序節點的列表

例如:

當前節點列表的值:1 - 2 - 2 - 3 - 5 值來添加:2 結果:1 - 2 - 2 - 2 - 3 - 5

我提出節點列表 我的代碼:一類叫做

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

添加一個節點時,「n」是小於在節點基於列表的第一個元素就是容易弄清楚,但我不能似乎想出如何如果不是這樣,那就做吧。

其他信息:

該列表可以包含重複項。 類NodeList不能有比我包括的更多的實例變量。

+0

嘗試使用列表。每當用戶調用Add(int n)時,添加值並對其進行排序。 –

回答

1

假設你想保持這種一成不變的,總是要創建新實例,其他部分可以有這樣的:

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

他想要對列表進行排序。 – Linvi

+0

列表將被排序。當添加將在尾部被調用時,檢查將遞歸地運行以達到要被替換的正確尾部。 –

+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方法中只有一個參數完成嗎? – FrankK

+0

公共'Add'方法只有1個參數。 '公共NodeList添加(int值)' – Linvi

+0

是你想要的嗎? – Linvi