** 你好! 本篇文章将用C#向你讲述一个完整的顺序表**
网上有很多关于c/c++关于线性表的内容,但C#的却很少,因为C#有自己的list,里面已经封装好了,下面我将用我自己写的代码创建一个自己的Mylist
上一个博客说了线性表中的顺序表,这次我们继续链表
上个博客的传送门:https://blog.csdn.net/zzzsss123333/article/details/106711430
这次的内容更加的完整
里面的item代表要存储的内容
next代表下一个要连接的节点
然后分别声明属性
并且提供3个重载的构造函数(作用往下看)
first为头节点
构造函数是为了当我们new的时候初始化头节点为空用的
基本上所有的方法都大同小异,知道插入元素的方法后就可以尝试着写出剩下的方法了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp7
{
class Linklist<T> : ILinelist<T>
{
private Node<T> first;
public Node<T> First
{
get { return this.first; }
set { this.first = value; }
}
public Linklist()
{
this.first = null;
}
public void Add(T item)
{
Node<T> myNode = new Node<T>(item);
if (First == null)
{
First = myNode;
return;
}
Node<T> node = First;
while (node.Next != null)
{
node = node.Next;
}
node.Next = myNode;
}
public void Clear()
{
First = null;
}
public int GetIndex(T item)
{
Node<T> node = First;
int index = 0;
while (!item.Equals(node.Item))
{
index++;
node = node.Next;
if (node == null)
{
throw new Exception("没有该数据");
}
}
return index;
}
public T GetItem(int index)
{
int count = 0;
Node<T> node = First;
while (count != index)
{
count++;
node = node.Next;
if (node == null)
{
throw new Exception("没有该数据");
}
}
return node.Item;
}
public void SetItem(int index,T item)
{
int count = 0;
Node<T> node = First;
while (count != index)
{
count++;
node = node.Next;
if (node == null)
{
throw new Exception("没有该数据");
}
}
node.Item = item;
}
public T this[int index]
{
get { return GetItem(index); }
set { SetItem(index, value); }
}
public int GetLength()
{
if (First == null)
{
return 0;
}
int count = 1;
Node<T> node = First;
while (node.Next != null)
{
count++;
node = node.Next;
}
return count;
}
public void Insert(T item,int index)
{
if (index >= 1)
{
Node<T> node = First;
Node<T> m = new Node<T>();//存储上一个节点
int count = 0;
while (count != index)
{
count++;
m = node;
node = node.Next;
if (node == null)
{
throw new Exception("没有该数据");
}
}
Node<T> myNode = new Node<T>(node, item);//new一个要插入的节点,尾相接
m.Next = myNode;//首相接
return;
}
throw new Exception("index不在范围内");
}
public void Remove(T item)
{
Node<T> node = First;
Node<T> m = new Node<T>();
if (item.Equals(First.Item))
{
First = First.Next;
return;
}
while (!item.Equals(node.Item))
{
m = node;
node = node.Next;
if (node == null)
{
throw new Exception("没有该数据");
}
}
m.Next = node.Next;
}
public void RemoveAt(int index)
{
if (index >= 0 && index < GetLength())
{
int count = 0;
Node<T> node = First;
Node<T> m = new Node<T>();
while (count != index)
{
count++;
m = node;
node = node.Next;
}
m.Next = node.Next;
return;
}
throw new Exception("index超出范围");
}
}
}