LinkedList底层是链表实现,首先要理解链表的基本概念和基本操作。
以双向链表为例:
链表中,链表是由节点组成的,每个节点由3部分构成,前置节点,节点的内容,后置节点。
Java底层的LinkedList是实现List接口的。
下面我们自己实现LinkedList的底层实现,主要是要理解双向链表的原理。
package cn.zhouxj.collection; public class MyLinkedList { private Node first; private Node last; private int size; public int size() { return size; } //自己实现add,在末尾增加 public void add(Object obj){ Node n = new Node(); //首先考虑当前链表是否为空 if(first == null){ n.setObj(obj); first = n; last = n;//若链表中只有一个节点,这个节点既是firstNode,也是lastNode节点 }else{ n.setPrevious(last); n.setObj(obj); n.setNext(null); last.setNext(n); last = n; } size++; } //自己实现add public void add(int index,Object obj){ rangeCheck(index); Node tmp = node(index); Node newNode = new Node(); newNode.obj = obj; if(tmp !=null){ newNode.previous = tmp.previous; newNode.next = tmp; tmp.previous.next = newNode; tmp.previous = newNode; } } //自己实现get(),连表中使用get方法,需要遍历链表 public Object get(int index) { //index越界处理 rangeCheck(index); Node tmp = node(index); if(tmp!=null){ return tmp.obj; }else return null; } //自己实现remove public void remove(int index){ rangeCheck(index); //首先找到这个节点 Node tmp = node(index); tmp.previous.next = tmp.next; tmp.next.previous = tmp.previous; size--; } //检查index是不是越界 private void rangeCheck(int index){ if (index >= size) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } } //根据索引找到指定的节点 public Node node(int index){ Node tmp = null; if (first != null) { tmp = first; for(int i =0;i<index;i++){ tmp = tmp.next; } } return tmp; } public static void main(String[] args){ MyLinkedList list = new MyLinkedList(); list.add("aaa"); list.add("bbb"); list.add(1,"BBBB"); list.add("ccc"); System.out.println(list.get(1)); } }