/// <summary> /// 在尾节点前插入新节点 /// </summary> /// <param name="value"></param> public void AddBefore(T value) { DbNode <T> dbNode = new DbNode <T>(value); if (this.head == null) { this.head = dbNode; } else if (this.head.NextNode == null) { dbNode.NextNode = this.head; this.head.PrevNode = dbNode; this.head = dbNode; } else { DbNode <T> lastNode = GetNodeByIndex(this.count - 1); DbNode <T> lastSecondNode = lastNode.PrevNode;//倒数第二个 //调整倒数第二个节点 lastSecondNode.NextNode = dbNode; dbNode.PrevNode = lastSecondNode; //调整倒数第一个节点 lastNode.PrevNode = dbNode; dbNode.NextNode = lastNode; } this.count++; }
/// <summary> /// 在指定位置前插入新节点 /// </summary> /// <param name="index">索引</param> /// <param name="value"></param> public void InsertBefore(int index, T value) { DbNode <T> dbNode = new DbNode <T>(value); if (index < 0 || index > this.count) { throw new ArgumentOutOfRangeException("index", "索引超出范围"); } else if (index == 0) { if (this.head == null) { this.head = dbNode; } else { this.head.PrevNode = dbNode; dbNode.NextNode = this.head; this.head = dbNode; } } else { DbNode <T> currNode = GetNodeByIndex(index); DbNode <T> prevNode = currNode.PrevNode; currNode.PrevNode = dbNode; prevNode.NextNode = dbNode; dbNode.PrevNode = prevNode; dbNode.NextNode = currNode; } this.count++; }
private DbNode <T> GetNodeByIndex(int index) { if (index < 0 || index > this.count) { throw new ArgumentOutOfRangeException("index", "索引超出范围"); } DbNode <T> dbNode = this.head; for (int i = 0; i < index; i++) { dbNode = dbNode.NextNode; } return(dbNode); }
/// <summary> /// 在末尾添加节点 /// </summary> /// <param name="value"></param> public void AddAfter(T value) { DbNode <T> dbNode = new DbNode <T>(value); if (this.head == null) { this.head = dbNode; } else { DbNode <T> lastNode = GetNodeByIndex(this.count - 1); lastNode.NextNode = dbNode; dbNode.PrevNode = lastNode; } this.count++; }
/// <summary> /// 移除指定位置节点 /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { if (index < 0 || index > this.count) { throw new ArgumentOutOfRangeException("index", "索引超出范围"); } else if (index == 0) { this.head = this.head?.NextNode; } else { DbNode <T> delNode = GetNodeByIndex(index); DbNode <T> nextNode = delNode.NextNode; DbNode <T> prevNode = delNode.PrevNode; prevNode.NextNode = nextNode; if (nextNode != null) { nextNode.PrevNode = prevNode; } delNode = null; } this.count--; }
public MyDoubleLinkedList() { count = 0; head = null; }