JDK中的LinkedList 里的属性
Node first ;
Node last ;
int size;
在源码中的查找,用到了二分查找,先判断要查找的索引值index,和size比较大小,再判断是从first节点还是last节点开始查找
自己实现的LinkedList
public class MyLinkedList { // 链表查询的开始节点 private Node first; // 链表默认从末尾节点开始添加新的节点 private Node last; //当前节点的个数 private int size; public void add(Object obj) { Node newNode = new Node(); newNode.value = obj; if (first == null) { first = newNode; last = newNode; } else { last.next = newNode; newNode.prev = last; last = newNode; } size++; } public void remove(int index) { checkElementIndex(index); if (index == 0) { // 第一个节点 first = first.next; if (first != null) first.prev = null; } else if (index == size - 1) { // 最后一个节点 last = last.prev; last.next = null; } else { Node current = getNode(index); Node node1 = current.prev; Node node3 = current.next; node1.next = node3; node3.prev = node1; } size--; } public Node getNode(int index) { Node node = first; for (int i = 0; i < index; i++) { node = node.next; } return node; } public Object get(int index) { checkElementIndex(index); return getNode(index).value; } public int getSize() { return size; } public static void main(String[] args) { MyLinkedList myLinkedList = new MyLinkedList(); myLinkedList.add("A"); myLinkedList.add("B"); myLinkedList.add("C"); myLinkedList.add("D"); myLinkedList.remove(2); for (int i = 0; i < myLinkedList.getSize(); i++) { System.out.println(myLinkedList.get(i)); } } private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException("查询越界啦!"); } private boolean isElementIndex(int index) { return index >= 0 && index < size; } private class Node { Node prev; Node next; Object value; } }