2016-04-26 74 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