自己根据java的LinkedList源码编写的一个简单的LinkedList实现
自己实现了一个简单的LinkedList
/**
* Create by andy on 2018-07-03 11:44
* 根据 {@link java.util.LinkedList}源码 写了一个简单的实现,方便理解设计流程
* 该类是线程不安全的
*/
public class FrameLinkedList<E> {
private Node<E> first;
private Node<E> last;
private int size;
public int getSize() {
return size;
}
public E getFirst() {
if (first == null)
return null;
return first.item;
}
public E getLast() {
if (last == null)
return null;
return last.item;
}
/**
* 根据元素位置取元素的值
* 从这个例子中就可以看出来,为什么LinkedList获取元素比较慢,因为每次取出元素都有进行一次循环!!!!
*
* @param index
* @return
*/
public E get(int index) {
if (index < 0)
throw new IllegalArgumentException("参数不能小于0");
if (index >= size)
throw new IllegalArgumentException("参数太大了,当前集合最大长度为:" + size);
//如果索引小于当前元素个数的一半,就从头部开始循环,否则从尾部开始循环
Node<E> node = first;
if (index < size >> 1) {
//把头给节点,便于下面递归循环
for (int i = 0; i < index; i++) {
node = node.next;
}
} else {
//把尾给节点,便于下面递归循环
node = last;
for (int i = size - 1; i > index; i--) {
node = node.prev;
}
}
return node.item;
}
public void add(E e) {
if (size == 0) {
//第一次添加对象
Node<E> curr = new Node<>(e, null, null);
curr.item = e; //当前对象
first = curr;
last = curr;
} else {
Node<E> curr = new Node<>(e, last, null);
last.next = curr;
last = curr;
}
size++;
}
public boolean remove(E e) {
if (size == 0) return false;
//分两种来处理防止e为null的时候出现空指针异常
if (e == null) {
for (Node<E> n = first; n != null; n = n.next) {
if (n.item == null) {
remove(n);
return true;
}
}
} else {
for (Node<E> n = first; n != null; n = n.next) {
if (e.equals(n.item)) {
remove(n);
return true;
}
}
}
return false;
}
private void remove(Node<E> node) {
Node<E> prev = node.prev;
Node<E> next = node.next;
if (prev == null) {
//移除的是第一个
node.next = null;
next.prev = null;
first = next;
} else if (next == null) {
//移除的是最后一个
node.prev = null;
prev.next = null;
last = prev;
} else {
//移除的是中间
node.prev = null;
node.next = null;
prev.next = next;
next.prev = prev;
}
node.item = null; //便于回收item
size--;
}
private static class Node<E> {
E item; //当前对象
Node<E> prev; //上一个对象的Node
Node<E> next; //下一个对象的Node
Node(E item, Node<E> prev, Node<E> next) {
this.item = item;
this.prev = prev;
this.next = next;
}
}
public static void main(String[] args) {
FrameLinkedList<String> list = new FrameLinkedList<>();
list.add("a1");
list.add("a2");
list.add("a3");
list.add("a4");
list.add("a5");
for (int i = 0; i < list.getSize(); i++) {
System.out.println(list.get(i));
}
System.out.println("-------");
list.remove(list.get(4));
for (int i = 0; i < list.getSize(); i++) {
System.out.println(list.get(i));
}
}
}