c#将值添加到基于排序节点的列表中

时间:2016-04-26 10:51:11

标签: c# nodes

我试图制作一个' Add(int n)'将节点添加到基于节点的列表的方法。列表已排序,我想在正确的位置添加节点,以便在添加节点后仍然对其进行排序。

示例:

当前节点列表值:1 - 2 - 2 - 3 - 5 要添加的值:2 结果:1 - 2 - 2 - 2 - 3 - 5

我创建了一个名为:nodeList的类 我的代码:

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类不能包含比我包含的实例变量更多的实例变量。

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:1)

假设你想保持这种不可变性并且总是想要创建新实例,那么部分就可以拥有:

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