/// <summary> /// 在指定位置插入一个数据 /// </summary> /// <param name="index">插入的位置</param> /// <param name="data">插入的值</param> public void Insert(int index, T data) { if (index < 0 || index > count) { throw new Exception("下标越界"); } DoubleNode <T> node = head; int i = 0; while (i <= index) { node = node.next; i++; } DoubleNode <T> temp = new DoubleNode <T>(data); //新节点的pre指向插入节点的pre temp.pre = node.pre; //插入节点的pre的next指向新节点 node.pre.next = temp; //插入节点的pre的next指向新节点 node.pre = temp; //新节点的next指向插入的节点 temp.next = node; count++; }
/// <summary> /// 往链表中新添加一个数据 /// </summary> /// <param name="data">新加的数据</param> public void Add(T data) { /*DoubleNode<T> node = head; * int i = 0; * while (node.next!=tail) * { * i++; * node = node.next; * } * Insert(i, data);*/ DoubleNode <T> temp = new DoubleNode <T>(data); //新节点的pre指向插入节点的pre temp.pre = tail.pre; //插入节点的pre的next指向新节点 tail.pre.next = temp; //插入节点的pre的next指向新节点 tail.pre = temp; //新节点的next指向插入的节点 temp.next = tail; count++; }
int count; //有效元素个数 //构造函数初始化 public DoubleLinkList() { head = new DoubleNode <T>(); tail = new DoubleNode <T>(); //头结点的next指向尾节点 head.next = tail; //尾节点的pre指向头结点 tail.pre = head; count = 0; }
/// <summary> /// 链表转数组 /// </summary> /// <returns></returns> public T[] ToArray() { T[] data = new T[count]; int i = 0; DoubleNode <T> index = head.next; while (index != tail) { data[i++] = index.data; index = index.next; } return(data); }
/// <summary> /// 通过值获取数据的下标 /// </summary> /// <param name="data"></param> /// <returns></returns> int GetIndexByValue(T data) { int i = 0; DoubleNode <T> index = head.next; while (index != tail) { if (index.data.Equals(data)) { return(i); } index = index.next; i++; } return(-1); }
/// <summary> /// 删除指定位置的数据 /// </summary> /// <param name="index">删除的下标</param> public void RemoveAt(int index) { if (index < 0 || index >= count) { throw new Exception("下标越界"); } int i = 0; DoubleNode <T> node = head; while (i <= index) { node = node.next; i++; } node.pre.next = node.next; node.next.pre = node.pre; count--; }
public DoubleNode(T data) { this.data = data; next = null; pre = null; }
public DoubleNode() { data = default; next = null; pre = null; }