【7】双向循环链表
- 1、双向循环链表
- 2、添加
- 3、删除
1、双向循环链表
🖊 头节点的
prev
指向尾节点
🖊 尾节点的next
指向头节点
2、添加
/*** 往索引位置添加元素*/@Overridepublic void add(int index, E element) {checkIndex4Add(index);if (index == size) { // 添加到尾节点位置Node<E> oldLast = last;// 双向循环链表的尾节点的next指向头节点last = new Node<>(element, last, first);if (oldLast == null) { // 添加第一个节点的时候first = last;first.next = first;first.prev = first;} else {oldLast.next = last;first.prev = last;}} else {Node<E> next = node(index);Node<E> prev = next.prev;Node<E> newNode = new Node<>(element, prev, next);next.prev = newNode;prev.next = newNode;if (next == first) { // index == 0first = newNode;}}size++;}
3、删除
/*** 删除索引位置的元素*/@Overridepublic E remove(int index) {checkIndex(index);Node<E> delNode = first;if (size == 1) {first = last = null;} else {delNode = node(index);Node<E> prev = delNode.prev;Node<E> next = delNode.next;prev.next = next;next.prev = prev;if (first == delNode) {first = next;}if (last == delNode) {last = prev;}}size--;return delNode.element;}
🖊 双向循环链表完整代码