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



我试图创建一个"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 不能有比我包含的更多的实例变量。

假设你想保持这个不可变并且总是想创建新实例,否则部分可以有这个:

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

如果你真的想使用你的结构,你可以使用以下代码。它使用递归函数来迭代不同的元素,直到正确的节点。

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

最新更新