数据结构——链表
链表节点类
namespace 单链表
{
class Node<T>
{
private T date;
private Node<T> next;
public Node()
{
date = default(T);
}
public Node(T value, Node<T> next)
{
this.date = value;
this.next = next;
}
public Node(T value)
{
this.date = value;
this.next = null;
}
public Node(Node<T> next)
{
this.next = next;
this.date = default(T);
}
public T Date
{
get { return date; }
set { date = value; }
}
public Node<T> Next
{
get { return next; }
set { next = value; }
}
}
}
- 相关接口
namespace 单链表
{
interface Interface1<T>
{
int GetLength();
void Clear();
bool IsEmpty();
void Add(T item);
void Insert(T item, int index);
void Delegate(int index);
T this[int index] { get; }
T GetEle(int index);
int Locate(T value);
}
}
链表类
namespace 单链表
{
class linkList<T> : Interface1<T>
{
private Node<T> head = new Node<T>();
public linkList()
{
head = null;
}
public T this[int index]
{
get
{
Node<T> tempNode =head;
for(int i=1;i<=index;i++)
{
tempNode = tempNode.Next;
}
return tempNode.Date;
}
}
public void Add(T item)
{
Node<T> newNode = new Node<T>(item);
if (head == null)
{
head = newNode;
}
else
{
Node<T> tempNode = new Node<T>();
tempNode = head;
while(true)
{
if (tempNode.Next != null)
{
tempNode = tempNode.Next;
}
else
{
break;
}
}
tempNode.Next = newNode;
}
}
public void Clear()
{
throw new NotImplementedException();
}
public void Delegate(int index)
{
T date = default(T);
if(index==0)
{
date = head.Date;
head = head.Next;
}
else
{
Node<T> tempNode =head;
Node<T> preNode = new Node<T>();
Node<T> curNode = new Node<T>();
for (int i=1;i<=index-1;i++)
{
tempNode = tempNode.Next;
}
preNode = tempNode;
curNode = tempNode.Next.Next;
preNode.Next = curNode;
}
}
public T GetEle(int index)
{
return this[index];
}
public int GetLength()
{
Node<T> tempNode = head;
int count = 1;
while(true)
{
tempNode = tempNode.Next;
if(tempNode!=null)
{
count++;
}
else
{
break;
}
}
return count;
}
public void Insert(T item, int index)
{
Node<T> newNode = new Node<T>(item);
if(index == 0)
{
newNode.Next = head;
head = newNode;
}
else
{
Node<T> tempNode =head;
for(int i=1;i<=index-1;i++)
{
tempNode = tempNode.Next;
}
Node<T> preNode = tempNode;
Node<T> curNode = tempNode.Next;
preNode.Next = newNode;
newNode.Next = curNode;
}
}
public bool IsEmpty()
{
throw new NotImplementedException();
}
public int Locate(T value)
{
throw new NotImplementedException();
}
}
}
主函数
namespace 单链表
{
class Program
{
static void Main(string[] args)
{
linkList<string> list = new linkList<string>();
list.Add("123");
list.Add("456");
list.Add("789");
// Console.WriteLine(list.GetLength());
// Console.WriteLine(list[0]);
// list.Insert("0", 1);
list.Delegate(2);
for (int i=0;i<list.GetLength();i++)
{
Console.WriteLine(list[i]);
}
Console.ReadKey();
}
}
}
本文介绍了一个简单的单链表实现,包括链表节点类定义、链表类实现及相关接口设计。主要内容涵盖链表的基本操作,如添加元素、删除指定位置元素等。

被折叠的 条评论
为什么被折叠?



