手写LInkedLsit简单实现
package day01.linkedList模拟;
/**
* @author feng
*
*/
public class Node {
// 上一个节点的地址
private Node pre ;
//当前存入的元素
private Object obj;
//下一个元素的地址
private Node next;
public Node getPre() {
return pre;
}
public void setPre(Node pre) {
this.pre = pre;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"pre=" + pre +
", obj=" + obj +
", next=" + next +
'}';
}
}
public class MylinkedList {
//首节点
Node first;
// 未节点
Node last;
// 计数器
int count = 0;
public MylinkedList() {
}
//添加元素
public void add(Object o) {
if (first == null) {
// 创捷节点对象
Node n = new Node();
// 头指针为空
n.setPre(null);
// 首节点中添加元素
n.setObj(o);
// 尾节点
n.setNext(null);
// 头尾节点均为首节点
first = n;
last = n;
} else {
// 首节点不为空
Node n = new Node();
// 前一个元素的地址
n.setPre(last);
n.setObj(o);
//下一个元素为空
n.setNext(null);
//尾元素节点指向
last.setNext(n);
last = n;
}
count++;
}
//给到元素的数量
public int getCount() {
return count;
}
// 通过下标获取元素
public Object get(int index){
// 获取链表的首元素
Node n = first;
for (int i = 0; i < index ; i++) {
n = n.getNext();
}
return n.getObj();
}
}
分析源码
定义节点
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
add()方法
public boolean add(E e) {
linkLast(e);
return true;
}
last==null,定义了一个新的节点。如果不存在新节点,last指向新节点的地址,否则,将尾节点指向新节点的地址。
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
size()
public int size() {
return size;
}
get()
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
查找元素:(size>>1),折半查找,提高效率
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}