Reputation: 21
I have been tasked with creating a Monopoly game using a Linked List (I am a University Student) as the basis for the board, I have implemented a Linked List adding nodes to the board to then WriteLine in a console window. There doesn't seem to be any visible errors in the code, but I seemed to have implemented some part of the code incorrectly as only the "Go" string is printing out in the console window? Any advice would be much appreciated.
Here's the code:
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();
}
}
}
}
Upvotes: 1
Views: 140
Reputation: 564413
Your write method isn't correct. You'd need to iterate through the items:
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)
}
Note that your old method would actually run forever, provided you hit a key. It should print "Go"
repeatedly every time you press a key, as it never iterates through the list.
For a "real world" project, I'd actually recommend using LinkedList<T>
instead of implementing your own linked list, as well.
Upvotes: 1