-1
我的鏈接列表程序從頭開始。我已經成功地讓我的列表中顯示,但現在我想顯示其在我的情況會出現在列表中爲int,項目數3鏈接列表方法幫助c#
能有人給我一些指點
主要:
class Program
{
static void Main(string[] args)
{
LinkList testList = new LinkList();
testList.AddItem(5);
testList.AddItem(10);
testList.AddItem(12);
testList.DisplayItems();
Console.WriteLine(testList.NumberOfItems()); /// Still to do
Console.ReadKey();
}
}
}
班鏈表:
class LinkList
{
private Link list = null; //default value – empty list
public void AddItem(int item) //add item to front of list
{
list = new Link(item, list);
}
public void DisplayItems() // Displays items in list
{
Link temp = list;
while (temp != null)
{
Console.WriteLine(temp.Data);
temp = temp.Next;
}
}
public int NumberOfItems() // returns number of items in list
{
Link temp = list;
while (temp != null)
{
/// How can i display the number of items in list as an int?
}
}
}
}
班鏈路:
class Link
{
private int data;
private Link next;
public Link(int item) //constructor with an item
{
data = item;
next = null;
}
public Link(int item, Link list) //constructor with item and list
{
data = item;
next = list;
}
public int Data //property for data
{
set { this.data = value; }
get { return this.data; }
}
public Link Next //property for next
{
set { this.next = value; }
get { return this.next; }
}
}
}
你嘗試過什麼?你有什麼想法?你在哪裏堅持你的計數? – 2014-11-04 14:38:31
如果您知道如何遍歷列表並顯示項目,您知道如何遍歷列表並對它們進行計數。另外,如果你創建一個計數器並讓你的'AddItem'方法增加這個計數器,那麼'NumberOfItems'可以在O(1)而不是O(n)中實現。 – dcastro 2014-11-04 14:40:11
基本上你已經循環了你的列表(如顯示它所做的那樣)並增加一個內部計數器 – HimBromBeere 2014-11-04 14:41:09