0

目前我正在学习如何在 C# 中构建自己的链表。我创建了一个名为的函数,它AddTrees根据文本框输入将树添加到列表的末尾:tree_name、、tree_height和。我请求帮助我如何修改我的函数以实现一种在当前和?之间插入树的方法tree_pricetree_instockcurrent.next_tree

例子

在此处输入图像描述

public class TheTrees
{
    private string tree_type = " ";
    private int tree_height = 0;
    public double tree_price = 0;
    private int tree_instock = 0;            

    public TheTrees next_tree;

    public TheTrees(string newtree, int newheight, int newinstock, double newprice)
    {
        tree_type = newtree;
        tree_height = newheight;
        tree_price = newprice;
        tree_instock = newinstock;                

        next_tree = null;
    }

    public override string ToString()
    {
        return tree_type + " " + tree_height + " " + 
               tree_price + " " + tree_instock;
    }
}

public class ListForTrees
{
    public TheTrees first_tree;
    public TheTrees last_tree;
    public int count = 0;

    public ListForTrees(TheTrees new_tree)
    {
        first_tree = new_tree;
        last_tree = new_tree;
        count = 1;
    }

    public ListForTrees()
    {
    }

    public void AddTree(TheTrees new_tree)
    {
        TheTrees current = first_tree;

        if (count == 0)
        {
            first_tree = new_tree;
            last_tree = new_tree;
            count = 1;
        }
        else if (count != 0)
        {
            if (new_tree.tree_price <= first_tree.tree_price)
            {
                new_tree.next_tree = first_tree;
                first_tree = new_tree;
            } 
            else if (new_tree.tree_price >= last_tree.tree_price)
            {
                last_tree.next_tree = new_tree;
                last_tree = new_tree;
            }
            else
            {
               while (new_tree.tree_price > current.next_tree.tree_price)
               {
                   current = current.next_tree;
               }

               new_tree.next_tree = current.next_tree;
               current.next_tree = new_tree;
            }

            count++;
       }
   }

   public void ClearTrees()
   {
        first_tree = null;
        count = 0;
   }
}
4

1 回答 1

0

我不知道你为什么要ListForTrees上课,因为你有一个链表。

var oak = new TheTrees("Oak", 6, 2.00, 6);
var cypress = new TheTrees("Cypress", 20, 80.00, 2);
var evergreen = new TheTrees("Evergreen", 25, 50.00, 6);

//add evergreen after cypress
oak.next_tree = evergreeen;

//insert cypress
cypress.next_tree = oak.next_tree;
oak.next_tree = cypress;
于 2012-12-09T04:00:12.143 回答