/// <summary>
/// 鏈表是線性表(A1,A2,A3,A4,A5,A6)對應的鏈式存儲結構
/// H-->|A1|-->|A2|-->|Ai-1|-->|Ai|-->|An|
/// H 是虛擬節點,相當於根節點(Root)
/// An = {data, next};
/// </summary>
/// <typeparam name="T"></typeparam>
public class Node<T>
{
/// <summary>
/// 數據
/// </summary>
public T Data { set; get; }
/// <summary>
/// 後驅節點的引用
/// </summary>
public Node<T> Next { set; get; }
public Node()
{
Data = default(T);
Next = null;
}
public Node(T data)
{
this.Data = data;
}
public Node(T data, Node<T> node):this(data)
{
this.Next = node;
}
}
public class MyList<T>
{
/// <summary>
/// 頭節點,也可以說是虛擬的根節點
/// </summary>
public Node<T> Head { set; get; }
public MyList()
{
Head = new Node<T>();
}
/// <summary>
/// 鏈表的length屬性
/// </summary>
public int Length
{
get
{
Node<T> point = Head;
int len = 0;
while(point.Next!= null)
{
len++;
point = point.Next;
}
return len;
}
}
/// <summary>
/// 清空單鏈表
/// </summary>
public void Clear()
{
Head.Next = null;
}
public bool IsEmpty
{
get
{
return this.Length == 0 ? true : false;
}
}
public void Add(T item)
{
Node<T> node = new Node<T>(item);
// 一個節點都沒有
if (Head.Next == null)
{
Head.Next = node;
}
else
{
Node<T> point = Head.Next;
while(point.Next != null)
{
point = point.Next;
}
point.Next = node;
}
}
/// <summary>
/// 根據 索引(從0開始) 查找元素
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public T GetItem(int index)
{
if(index < 0 || index >= this.Length)
{
throw new Exception("the index is error.");
}
if(!this.IsEmpty)
{
Node<T> point = Head.Next;
int j = 0;
while (point!= null && j< index)
{
if(j++ == index)
{
break;
}
point = point.Next;
}
return point.Data;
}
else
{
throw new Exception("the list is empty.");
}
}
/// <summary>
/// 根據value查找下標(從0開始)
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public int Locate(T value)