【发布时间】:2019-03-15 14:58:15
【问题描述】:
我正在尝试创建一个链接列表,类似于鸟类调查类型的东西,并且我试图有一个最终输出,它返回我输入的所有物种以及我输入每个物种的次数。现在输出计算了我输入的每只不同的鸟,但它没有在报告的末尾为我输入的每只鸟单独计数,我不知道该怎么做。我已经为此烦恼了好几个小时了,我觉得我已经很接近了,如果可以请帮助
class Program
{
public class Node
{
/* You add the type of bird and a count of
* how many times that bird is said.
* Then you use a method to print out
* the types of birds and how many times each bird was said*/
public string bird;
public Node next;
public Node(string i)
{
bird = i;
next = null;
}
public void getReport()
{
Console.Write("|" + bird + "|->");
if (next != null)
{
next.getReport();
}
}
public void AddToEnd(string bird)
{
if (next == null)
{
next = new Node(bird);
}
else
{
next.AddToEnd(bird);
}
}
public class BirdList
{
public Node headNode;
public BirdList()
{
headNode = null;
}
public void AddToEnd(string bird) //method to add to the end of a list
{
if (headNode == null)
{
headNode = new Node(bird);
}
else
{
headNode.AddToEnd(bird);
}
}
public void AddToBeginning(string bird) //add to the beginning of a list
{
if (headNode == null)
{
headNode = new Node(bird);
}
else
{
Node temp = new Node(bird);
temp.next = headNode;
headNode = temp;
}
}
public void getReport()
{
if (headNode != null)
{
headNode.getReport();
}
}
public int getCount(string bird)
{
Node current = headNode;
int count = 0;
while (current!= null)
{
if (current.bird == bird)
{
count++;
}
current = current.next;
}
return count;
}
}
static void Main(string[] args)
{
BirdList birdList = new BirdList();
string userInput = "";
while (userInput != "done")
{
Console.WriteLine("Please enter a bird:");
userInput = Console.ReadLine();
if (userInput == "done")
{
break;
}
birdList.AddToEnd(userInput);
Console.WriteLine(birdList.getCount(userInput));
}
birdList.getReport();
Console.ReadLine();
输出看起来像这样:
【问题讨论】:
-
首先你真的不需要写你自己的链表。您可以使用
LinkedList<T>。其次,我不确定链接列表在这里是否最有意义。除非您需要添加鸟类的顺序,否则我只会使用Dictionary<string, int>来捕获鸟类和频率。现在,如果这是您需要滚动自己的链接列表的作业,那么请忽略。 -
不幸的是,分配是这样设置的:/使用 LinkedList
会容易得多
标签: c# linked-list counter