目前我正在学习如何在C#中构建自己的链表。我创建了一个名为AddTrees
的函数,它根据文本框输入在列表的末尾添加一个树:tree_name
,tree_height
,tree_price
和tree_instock
。我正在请求帮助我如何修改我的功能,以实现在当前和current.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;
}
}
答案 0 :(得分: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;