循环在节点链中

时间:2017-12-17 23:28:21

标签: c#

假设我有100个节点:

        Node<double> n1 = new Node<double>(1);
        Node<double> n2 = new Node<double>(2);
        Node<double> n3 = new Node<double>(3);
        Node<double> n4 = new Node<double>(4);
        Node<double> n5 = new Node<double>(5);
        Node<double> n6 = new Node<double>(6);
                       .
                       .
                       .
        Node<double> n100 = new Node<double>(100);

我想连接它们,然后我可以写:

        n1.SetNext(n2);
        n2.SetNext(n3);
        n3.SetNext(n4);
        n4.SetNext(n5);
        n5.SetNext(n6);
             .
             .
             .
        n99.SetNext(n100);

但是,我怎么能这样做一个循环呢?我试过像:

            Node<double> pos = n1;
            int i = 1;
            while (pos != null)
            {
                pos.SetValue(i);
                pos.SetNext(new Node<double>(0));
                pos = pos.GetNext();
                i++;
            }

1 个答案:

答案 0 :(得分:2)

List<Node<double>> nodes = new List<Node<double>>(100);

for (Int32 i = 1; i <= 100; ++i)
    nodes.Add(new Node<double>(i));

for (Int32 i = 0; i < 100; ++i)
    nodes[i].SetNext(nodes[i + 1]);

使用您的方法,我会选择:

Node<double> n = new Node<double>(0);
Int32 i = 1;

while (i <= 100)
{
    n.SetValue(i);
    n.SetNext(new Node<double>(0));
    n = n.GetNext();

    ++i;
}