简单的链表实现
Java LinkedList底层是基于双向链表来实现的,为了更好的理解其实现原理,自己对简单的链表结构做了Java实现,代码如下
class MyLinkedList<E>{
private int size = 0;
private Node<E> head;
private Node<E> last;
private Node<E> first;
public MyLinkedList() {
this.size = 0;
this.last = null;
this.first = null;
head = first;
}
public boolean add(E e){
linkLast(e);
return true;
}
public void reset(){
head = first;
}
public boolean hasNext(){
return head != last.next;
}
public E next(){
Node<E> temp = head;
head = temp.next;
return temp.item;
}
private void linkLast(E e) {
Node<E> la = last;
Node<E> newNode = new Node<E>(e, la, null);
last = newNode;
if (la == null){
head = newNode;
first = newNode;
} else {
la.next = newNode;
}
size++;
}
class Node<E>{
E item;
Node<E> pre;
Node<E> next;
public Node(E item, Node<E> pre, Node<E> next) {
this.item = item;
this.pre = pre;
this.next = next;
}
}
}