我的任务是使用链接列表(我是大学生)创建一个大富翁游戏作为董事会的基础,我已经实现了一个链接列表,在板上添加节点,然后在控制台窗口中添加WriteLine。代码中似乎没有任何明显的错误,但我似乎错误地实现了部分代码,因为只有“Go”字符串在控制台窗口中打印出来?任何建议都将不胜感激。
以下是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MonoPolyFin
{
public class Square
{
public Square next;
public string p;
public Square(string p)
{
this.p = p;
}
public class Board{
Square head;
Square current;
public void Add(Square s)
{
if (head == null)
{
head = s;
current = head;
}
else
{
current.next = s;
current = current.next;
}
}
public void Writrline()
{
while (head != null)
{
Console.WriteLine(head.p);
Console.ReadKey();
}
}
static void Main(string[] args)
{
Board list = new Board();
list.Add(new Square("Go"));
list.Add(new Square("Strand"));
list.Add(new Square("Trafalger Square"));
list.Add(new Square("Gas"));
list.Add(new Square("Leicester Square"));
list.Add(new Square("Piccadilly"));
list.Add(new Square("Card"));
list.Add(new Square("Regent Street"));
list.Add(new Square("Oxford"));
list.Add(new Square("Electric"));
list.Add(new Square("Mayfair"));
list.Add(new Square("Park Lane"));
list.Add(new Square("Jail"));
list.Add(new Square("Old Kent Road"));
list.Add(new Square("Whitechapel"));
list.Add(new Square("Water"));
list.Add(new Square("Islington"));
list.Add(new Square("Euston"));
list.Add(new Square("Card"));
list.Add(new Square("PallMall"));
list.Add(new Square("Whitehall"));
list.Add(new Square("Phone"));
list.Add(new Square("BowStreet"));
list.Add(new Square("VineStreet"));
list.Writrline();
}
}
}
}
答案 0 :(得分:1)
您的写入方法不正确。你需要遍历这些项目:
public void Writrline()
{
Square item = head; // Store the head - so you can modify it below
while (item != null)
{
Console.WriteLine(item.p);
item = item.next; // Move to next item in the list
}
Console.ReadKey(); // Read after the loop to pause (if you want to do this)
}
请注意,只要您按下某个键,您的旧方法就会实际运行永远。每按一次键,它都应重复打印"Go"
,因为它永远不会遍历列表。
对于“真实世界”项目,我实际上建议使用LinkedList<T>
,而不是实现自己的链接列表。