结点类:
关键处在C语言中用指针来指向下一个节点,C#是面向对象的,用节点类的一个属性(Next属性)来指向下一个节点对象
public class LinkNode<T>
{
#region 定义单链表数据结构
private T data;
public T Data
{
get { return data; }
set { data = value; }
}
private LinkNode<T> next;
public LinkNode<T> Next
{
get { return next; }
set { next = value; }
}
#endregion
public LinkNode()
{
this.data = default(T);
this.next = null;
}
public LinkNode(T data, LinkNode<T> next)
{
this.data = data;
this.next = next;
}
public LinkNode(T data)
{
next = null;
this.data = data;
}
public LinkNode(LinkNode<T> next)
{
this.next = next;
}
}
接口的定义
public interface IListDS<T>
{
int GetLength(); //求长度
void Clear(); //清空操作
bool IsEmpty(); //判断线性表是否为空
void Append(T item); //附加操作
void Insert(T item, int i); //插入操作
T Delete(int i); //删除操作
T GetElem(int i); //取表元
int Locate(T value); //按值查找
}
实现操作的类
class MyLinkList<T> : IListDS<T>
{
private LinkNode<T> head;//单链表的头指针
public MyLinkList()
{
head = null;
}
public LinkNode<T> Head
{
get { return head; }
set { head = value; }
}
/// <summary>
/// 计算长度
/// </summary>
/// <returns></returns>
public int GetLength()
{
int length = 0;
LinkNode<T> node = head;
while (node != null)
{
length++;
node = node.Next;
}
return length;
}
public void Clear()
{
head = null;
}
public bool IsEmpty()
{
if (head==null)
{
return true;
}
else
{
return false;
}
}
public void Append(T value)
{
LinkNode<T> p = new LinkNode<T>();
LinkNode<T> q = new LinkNode<T>(value);
//如果这是链表为空,则加入这个当表头
if (IsEmpty())
{
head = q;
return;
}
//找到最后一个元素
while (p.Next != null)
{
p = p.Next;
}
p.Next = q;
}
//index从0开始,index=0则插入第一个元素,index=1则插入第二个原色
public void Insert(T value, int index)
{
LinkNode<T> p = head;
LinkNode<T> node = new LinkNode<T>(value);
int i = 0;
if (GetLength() < index)
{
return;
}
//定位
if (index == 0)
{
p = head;
}
while (i < index)
{
p = p.Next;
}
//插入
node.Next = p.Next;
p.Next = node;
}
//删除单链表的第i个结点
public T Delete(int i)
{
if (IsEmpty() || i < 0)
{
Console.WriteLine("Link is empty or Position is error!");
return default(T);
}
LinkNode<T> q = new LinkNode<T>();
if (i == 1)
{
q = head;
head = head.Next;
return q.Data;
}
LinkNode<T> p = head;
int j = 1;
while (p.Next != null && j < i)
{
++j;
q = p;
p = p.Next;
}
if (j == i)
{
q.Next = p.Next;
return p.Data;
}
else
{
Console.WriteLine("The ith node is not exist!");
return default(T);
}
}
public T GetElem(int index)
{
if (IsEmpty())
{
Console.WriteLine("List is empty!");
return default(T);
}
LinkNode<T> p = new LinkNode<T>();
p = head;
int j = 1;
while (p.Next != null && j < index)
{
++j;
p = p.Next;
}
if (j == index)
{
return p.Data;
}
else
{
Console.WriteLine("The ith node is not exist!");
return default(T);
}
}
public int Locate(T value)
{
int i = 0;
if (IsEmpty())
{
return -1;
}
LinkNode<T> p = head;
while(!p.Data.Equals(value)&&p.Next!=null)
{
p = p.Next;
i++;
}
if (p.Next == null)
{
return -1;
}
return i;
}
}