标签:code over one 链表 style 循环 pre color last
@Override public E remove(int index) { rangeCheck(index); Node<E> node = node(index); Node<E> prev = node.prev; Node<E> next = node.next; if (prev == null) { // index == 0 first = next; } else { prev.next = next; } if (next == null) { // index == size - 1 last = prev; } else { next.prev = prev; } size--; return node.element; }
@Override public void add(int index, E element) { rangeCheckForAdd(index); if (index == 0) { Node<E> newFirst = new Node<>(element, first); // 拿到最后一个节点 Node<E> last = (size == 0) ? newFirst : node(size - 1); last.next = newFirst; first = newFirst; } else { Node<E> prev = node(index - 1); prev.next = new Node<>(element, prev.next); } size++; }
@Override public E remove(int index) { rangeCheck(index); Node<E> node = first; if (index == 0) { if (size == 1) { first = null; } else { Node<E> last = node(size - 1); first = first.next; last.next = first; } } else { Node<E> prev = node(index - 1); node = prev.next; prev.next = node.next; } size--; return node.element; }
@Override public void add(int index, E element) { rangeCheckForAdd(index); // size == 0 // index == 0 if (index == size) { // 往最后面添加元素 Node<E> oldLast = last; last = new Node<>(oldLast, element, 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> node = new Node<>(prev, element, next); next.prev = node; prev.next = node; if (next == first) { // index == 0 first = node; } } size++; }
@Override public E remove(int index) { rangeCheck(index); return remove(node(index)); } private E remove(Node<E> node) { if (size == 1) { first = null; last = null; } else { Node<E> prev = node.prev; Node<E> next = node.next; prev.next = next; next.prev = prev; if (node == first) { // index == 0 first = next; } if (node == last) { // index == size - 1 last = prev; } } size--; return node.element; }
标签:code over one 链表 style 循环 pre color last
原文地址:https://www.cnblogs.com/ggnbnb/p/12179415.html