我在計算機科學的第二年。我們的老師要求我們實現MyLinkedList類(即使它在C#中默認存在),以提高我們的編程能力(算法)。一個鏈表的C#大小(源代碼)
我能夠實現代碼的很大一部分並對其進行測試,但是我無法實現返回鏈表大小的函數。
這是我對我所做的遠:
class MyLinkedList
{
class Element
{
public float value;
public Element next;
}
Element first;
public MyLinkedList()
{
first = null;
}
public void add(float x)
{
Element e = new Element();
e.value = x;
e.next = first;
first = e;
}
public float get(int i)
{
if (first == null)
{
throw new Exception("Empty list...no elements inside");
}
Element tmp = first;
for (int j = 0; j < i; ++j)
{
tmp = tmp.next;
if (tmp == null)
{
throw new Exception("...");
}
}
return tmp.value;
}
public int size()
{
// I'm completely lost on that one, I have no clue on how
// doing it.
}
}
class MainClass
{
public static void Main(string[] args)
{
//To test the code
MyLinkedList l = new MyLinkedList();
l.add(3);
l.add(5);
l.add(8);
Console.WriteLine(l.get(0));
Console.WriteLine(l.get(1));
Console.WriteLine(l.get(4));
}
}
只有'增加'計數,當你添加項目和'減少',當你刪除它。 –
爲什麼每次添加元素時都要先更改** **? – MickyD