主程序
class Program
{
static void Main(string[] args)
{
LinkList<string> seqList = new LinkList<string>();
seqList.Add("123");
seqList.Add("456");
seqList.Add("789");
Console.WriteLine(seqList.GetEle(0));
Console.WriteLine(seqList[0]);
seqList.Insert("777",1);
for (int i = 0; i < seqList.GetLength(); i++)
{
Console.Write(seqList[i]+" ");
}
seqList.Delete(0);
for (int i = 0; i < seqList.GetLength(); i++) {
Console.Write(seqList[i] + " ");
}
seqList.Clear();
Console.WriteLine(seqList.GetLength());
}
}
LinkList类
class LinkList<T>:IListDS<T>
{
private Node<T> head;//存储一个头结点
public LinkList()
{
head = null;
}
public int GetLength()
{
if (head == null) return 0;
Node<T> temp = head;
int count = 1;
while (true)
{
if (temp.Next != null)
{
count++;
temp = temp.Next;
}
else
{
break;
}
}
return count;
}
public void Clear()
{
head = null;
}
public bool IsEmpty()
{
return head == null;
}
public void Add(T item)
{
Node<T> newNode = new Node<T>(item);
if (head == null)//如果头结点为空,那么这个新的节点就是头节点
{
head = newNode;
}
//把新来的结点放到 链表的尾部
else
{
//如何访问链表的尾结点
Node<T> temp = head;//创建临时节点指向头节点
while (true)
{
if (temp.Next != null)
{
temp = temp.Next;
}
else
{
break;//这时temp是尾节点了
}
}
temp.Next = newNode;//把新来的结点放到 链表的尾部
}
}
public void Insert(T item, int index)//在index位置插入一个节点
{
Node<T> newNode = new Node<T>(item);
if (index == 0) //插入到头节点
{
newNode.Next = head;//newNode.Next指向第二个元素
head = newNode;//newNode为头节点
}
else
{
Node<T> temp = head;
for (int i = 1; i <=index-1; i++)//temp最终为index前一个节点
{
//让temp向后移动一个位置
temp = temp.Next;
}
Node<T> preNode = temp;//pre->new->curr
Node<T> currentNode = temp.Next;
preNode.Next = newNode;
newNode.Next = currentNode;
}
}
public T Delete(int index)
{
T data = default(T);
if (index == 0) //删除头结点
{
data = head.Data;
head = head.Next;
}
else
{
Node<T> temp = head;
for (int i = 1; i <= index - 1; i++) {
//让temp向后移动一个位置
temp = temp.Next;
}
Node<T> preNode = temp;
Node<T> currentNode = temp.Next;
data = currentNode.Data;
Node<T> nextNode = temp.Next.Next;
preNode.Next = nextNode;
}
return data;
}
public T this[int index]
{
get
{
Node<T> temp = head;
for (int i = 1; i <= index; i++) {
//让temp向后移动一个位置
temp = temp.Next;
}
return temp.Data;
}
}
public T GetEle(int index)
{
return this[index];
}
public int Locate(T value)
{
Node<T> temp = head;
if (temp == null)
{
return -1;
}
else
{
int index = 0;
while (true)
{
if (temp.Data.Equals(value))
{
return index;
}
else
{
if (temp.Next != null)
{
temp = temp.Next;
}
else
{
break;
}
}
}
return -1;
}
}
}
结点类
class Node<T>
{
private T data;//存储数据
private Node<T> next;//指针 用来指向下一个元素
public Node()
{
data = default(T);//获取默认值比如int为0
next = null;
}
public Node(T value)//插入一个元素
{
data = value;
next = null;
}
public Node(T value, Node<T> next)
{
this.data = value;
this.next = next;
}
public Node(Node<T> next)
{
this.next = next;
}
public T Data
{
get { return data; }
set { data = value; }
}
public Node<T> Next
{
get { return next; }
set { next = value; }
}
}