c# 自訂泛型鏈表類的詳解

來源:互聯網
上載者:User

(1)自訂泛型鏈表類。
複製代碼 代碼如下:public class GenericList<T>
{
private class Node
{
//當前節點值
private T data;
public T Data
{
get { return data; }
set { data = value; }
}
//節點的下一個節點
private Node next;
public Node Next
{
get { return next; }
set { next = value; }
}
//節點的上一個節點
private Node last;
public Node Last
{
get { return last; }
set { last = value; }
}
public Node(T t)
{
data = t;
next = null;
}
}
private Node firstNode;
private Node lastNode;
public void AddNode(T t)
{
Node node = new Node(t);
node.Last = lastNode;
if (lastNode != null)
lastNode.Next = node;
lastNode = node;
if (firstNode == null)
{
firstNode = node;
}
}
//要在自訂泛型集合上迭代
//必須實現該介面
public IEnumerator<T> GetEnumerator()
{
Node current = firstNode;
while (current != null)
{
//yield return運算式以枚舉對象返回
yield return current.Data;
current = current.Next;
}
}
}

(2)自訂泛型鏈表類調用。
複製代碼 代碼如下:class GenericListTestTwo
{
static void Main()
{
// 型別參數為int
GenericList<int> list = new GenericList<int>();
for (int a = 0; a < 5; a++)
{
list.AddNode(a);
}
foreach (int i in list)
{
System.Console.WriteLine(i);
}
//型別參數為string
GenericList<string> strList = new GenericList<string>();
strList.AddNode("First Node");
strList.AddNode("Second Node");
foreach(string s in strList)
{
System.Console.WriteLine(s);
}
Console.Read();
}
}

輸出如下:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.