public class DLinkList<T>
{
private DNode<T> head;//头指针
private int count; // 字段 ,不用这么加
//public DLinkList(T value)
//{
// head = new DNode<T>(value);
//}
/// <summary>
/// 新增元素
/// </summary>
/// <param name="value"></param>
public void Add(T value) {
DNode<T> newNode = new DNode<T>(value);
if (head == null) // 链表为空,头插入
{
head = newNode;
}
else { //插入到尾部
GetDNodeByIndex(count - 1).next = newNode;
}
this.count++;
}
/// <summary>
/// 删除指定索引处的值
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index) {
if (index == 0)
{
head = head.next;
}
else {
var prevNode = GetDNodeByIndex(index - 1);
if (prevNode.next == null) {
throw new ArgumentOutOfRangeException("index", "超出链表索引范围");
}
prevNode.next = prevNode.next.next;
}
count--;
}
/// <summary>
/// 在指定索引出插入值
/// </summary>
/// <param name="index">插入位置</param>
/// <param name="value">插入的值</param>
public void InsertAt(int index, T value)
{
if (index > count)
{
throw new ArgumentOutOfRangeException("index", "超出链表索引范围");
}
var tempNode = new DNode<T>(value);
if (index == 0)// 头部插入
{
if (head == null)
{
head = tempNode;
}
else
{
tempNode.next = head.next;
head = tempNode;
}
}
else {
var prev = GetDNodeByIndex(index - 1);
tempNode.next = prev.next;
prev.next = tempNode;
}
}
/// <summary>
/// 根据索引查找元素
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public DNode<T> GetDNodeByIndex(int index) {
if (index > this.count)
{
throw new ArgumentOutOfRangeException($"index({index})的值超过链表长度");
}
var p = head;
for (int i = 0; i < index; i++)
{
p = p.next;
}
return p;
}
public override string ToString()
{
var s = new StringBuilder();
for (DNode<T> p = head; p != null; p = p.next)
{
s.Append(p.ToString());
s.Append(" ");
}
return s.ToString();
}
public T this[int index]{
get { return GetDNodeByIndex(index).value; }
set { GetDNodeByIndex(index).value = value; }
}
/// <summary>
/// 获取链表总数
/// </summary>
public int Count => count;
public class DNode<T>
{
public DNode(T value)
{
this.value = value;
}
public T value;
public DNode<T> next;
public override string ToString()
{
return value.ToString();
}
}
}