随笔
自定义Linkedlist一个链表
public class setLinkedList<E> {
private jiedian diyi;
private jiedian zuihou;
private int size;
public void add(int indx,E element) {
chackrange(indx);
jiedian newjiedian = new jiedian(element);
jiedian laojie = getjiedian(indx);
if(laojie!=null) {
jiedian shang = laojie.shang;
shang.xia = newjiedian;
newjiedian.shang = shang;
newjiedian.xia = laojie;
laojie.shang = newjiedian;
}
}
public void remove(int indx) {
chackrange(indx);
jiedian jie = getjiedian(indx);
if(jie!=null) {
jiedian up = jie.shang ;
jiedian down = jie.xia ;
if(up!=null) {
up.xia =down;
}
if(down!=null) {
down.shang = up;
}
if(indx==0) {
diyi=down ;
}
if(indx==size-1) {
zuihou = up;
}
size--;
}
}
public E get(int indx) {
jiedian jie = getjiedian(indx);
chackrange(indx);
return jie!=null?(E)jie.element :null ;
}
private void chackrange(int indx) {
if(indx<=0||indx>size-1) {
throw new RuntimeException("索引数字不合法"+indx);
}
}
private jiedian getjiedian(int indx) {
chackrange(indx);
jiedian jie = null;
if(indx<=(size>>1)) {
jie = diyi;
for(int i=0;i<indx;i++) {
jie=jie.xia ;
}
}else {
jie = zuihou;
for(int i=size-1;i>indx;i-- ) {
jie = jie.shang;
}
}
return jie;
}
public void add(E element) {
jiedian jie = new jiedian(element);
if(diyi==null) {
//jie.shang=null;
//jie.xia=null;
diyi = jie;
zuihou = jie;
}else {
jie.shang=zuihou;
jie.xia =null;
zuihou.xia = jie;
zuihou = jie;
}
size++;
}
@Override
public String toString() {
//[a,b,c] diyi = a zuihou =c
StringBuilder sb = new StringBuilder("[");
jiedian ji = diyi;
while (ji!=null) {
sb.append(ji.element+"," );
ji = ji.xia;
}
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}
public static void main(String[] args) {
setLinkedList<String> li = new setLinkedList<>();
li.add("a");
li.add("b");
li.add("c");
li.add("d");
li.add("e");
li.add("f");
li.add("g");
System.out.println(li);
li.add(6, "xyz");
System.out.println(li);
}
}