class Node<T>
{
private T date; //資料域
private Node<T> next;//指針域
public T Date { get => date; set => date = value; }
internal Node<T> Next { get => next; set => next = value; }
public Node()
{
Next = null;
Date = default(T);
}
public Node(T date,Node<T> next)
{
this.Date = date;
this.Next = next;
}
public Node(T date)
{
Next = null;
this.Date = date;
}
public Node(Node<T> next)
{
this.Date = default(T);
this.Next = next;
}
}
/// <summary>
/// 連結清單類
/// </summary>
class LinkList<T>
{
private Node<T> head; //頭指針
private int count; //連結清單元素個數
public LinkList()
{
head=new Node<T>();//指向頭結點
count = 0;
}
//尾插法建立連結清單
public LinkList(params T[] list):this()
{
Node<T> last = head;
for (int i = 0; i < list.Length; i++)
{
Node<T> newNode = new Node<T>(list[i]);
last.Next = newNode;
last = last.Next;
}
count = list.Length;
}
//周遊單連結清單的元素
public void Traverse()
{
Node<T> temp = head;
for (int i = 0; i < count; i++)
{
temp = temp.Next;
Console.Write(temp.Date+" ");
}
Console.WriteLine();
}
//判斷是否為空
public bool IsEmepty()
{
return head.Next == null;
}
//擷取連結清單長度
public int GetLength()
{
return count;
}
//擷取元素索引位置
public int Index(T elem)
{
Node<T> temp = head;
for (int i = 0; i < count; i++)
{
temp = temp.Next;
if (temp.Date.Equals(elem))
{
return i;
}
}
Console.WriteLine("elem:{0}不在連結清單中", elem);
return -1;
}
//通過索引器擷取元素
public T this[int index]
{
get
{
if (index>=count||index<0)
{
throw new IndexOutOfRangeException();
}
Node<T> temp = head;
for (int i = 0; i <=index; i++)
{
temp = temp.Next;
}
return temp.Date;
}
}
//插入元素
public void Insert(int index,T elem)
{
Node<T> temp = head;
Node<T> newNode=new Node<T>(elem,null);
if (index >= count || index < 0)
{
throw new IndexOutOfRangeException();
}
//當為空連結清單的時候
if (temp.Next == null)
{
temp.Next = newNode;
count++;
}
else
{
for (int i = 0; i < index; i++)
{
temp = temp.Next;
}
newNode.Next = temp.Next;
temp.Next = newNode;
count++;
}
}
//删除元素
public void Delete(int index)
{
Node<T> temp = head;
if (head.Next == null)
{
Console.WriteLine("空表無法删除");
}
if (index >= count || index < 0)
{
throw new IndexOutOfRangeException();
}
for (int i = 0; i < index; i++)
{
temp = temp.Next;
}
temp.Next = temp.Next.Next;
count--;
}
}