[英]Insert Items in a Linked List
Currently I am learning how to build my own linked list in C#. 目前,我正在学习如何在C#中构建自己的链接列表。 I have created a function called
AddTrees
that adds a tree to the end of the the list according to textboxes input: tree_name
, tree_height
, tree_price
and tree_instock
. 我创建了一个名为
AddTrees
的函数,该函数根据输入的文本框将树添加到列表的末尾: tree_name
, tree_height
, tree_price
和tree_instock
。 I am requesting help in how I can modifiy my function to implementing a way to insert a tree between current and current.next_tree
? 我需要有关如何修改函数以实现在current和
current.next_tree
之间插入树的方法的帮助?
Example 例
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;
}
}
I don't know why you would have the ListForTrees
class at all, since you have a linked list. 我不知道为什么会有一个
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.