package _03;
import java.util.linkedList;
public class _3_10Demo {
// linkedList: 底层由双向链表构成 查询效率低 增删效率高 线程不安全
private Node first;
private Node last;
private int size;
public void add(Object obj){
Node node = new Node(obj);
if(this.first==null){
first = node;
last = node;
size ++;
}else{
node.previous = last;
node.next = null;
last.next = node;
last = node;
size ++;
}
}
public Object get(int index){
// int n = 0;
// Node node = first;
// while(n 一半 则从后往前找last 如果index <一半 则从前往后找
Node nd = getNode(index);
return nd!=null ? nd.element:null;
}
public Node getNode(int index){
if(index <0 || index >= size){
throw new RuntimeException("index 不合法");
}
Node nd;
if (index < size/2){
nd = first;
for(int i=0;iindex ;i--){
nd = nd.previous;
}
}
return nd;
}
public void remove(int index){
Node nd = getNode(index);
if (nd!=null){
Node up =nd.previous;
Node down =nd.next;
if(up!=null){
up.next = down;
}
if(down !=null){
down.previous = up;
}
if(index == 0){
first = down;
}
if(index == size-1){
last = up;
}
size--;
}
}
public void add(int index,Object obj){
Node nodeNew = new Node(obj);
Node node = getNode(index);
if(node!=null){
Node up = node.previous;
up.next = nodeNew;
nodeNew.previous=up;
node.previous=nodeNew;
nodeNew.next=node;
if(index==0){
first = node;
}
if(index ==size -1){
last = node;
}
size++;
}
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
Node nd = first;
while(nd !=null){
sb.append(nd.element+",");
nd = nd.next;
}
sb.setCharAt(sb.length()-1,']');
return sb.toString();
}
public static void main(String[] args) {
_3_10Demo ls = new _3_10Demo();
System.out.println(ls.toString());
System.out.println(ls.toString());
}
}