双链集合添加删除算法:
package com.linkes;
public class MyLinkeList {
/**
* 更多资料欢迎浏览凯哥学堂官网:http://kaige123.com
* @author 小沫
*/
/**
* 链表集合他是于双链条式进行引用上下家,好处可以知道上家和下家是谁
* 利于修改,可以从首部开始删除数据也可以从尾部删除。
* 即可从中间指定位置删除。
*/
private Object[] shou;
private Object[] wei;
public void add(Object obj) {
if (shou == null) {
shou = new Object[] { null, obj, null };
wei = shou;
} else {
Object[] objs = new Object[] { wei, obj, null };
wei[2] = objs;
wei = objs;
}
}
public void addlast(Object obj) {
add(obj);
}
public void addFirst(Object obj) {
if (shou == null) {
shou = new Object[] { null, obj, null };
wei = shou;
} else {
Object[] objs = new Object[] { null, obj, shou };
shou[0] = objs;
shou = objs;
}
}
public void removeAll(int delAll) {
if (delAll == 0) {
wei = null;
shou = null;
System.out.println("清除完成");
} else {
try {
throw new Exception("删除失败!delAll需为'0'");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public Object removeLast() {
Object obj = null;
if (wei == null) {
return false;
}
if (wei[0] == null) {
wei = null;
shou = null;
} else {
obj = wei[1];
wei = (Object[]) wei[0];
wei[2] = null;
}
return obj;
}
public Object removeFirst() {
Object obj = null;
obj = shou[1];
if (shou == null) {
return false;
}
if (shou[2] == null) {
wei = null;
shou = null;
} else {
shou = (Object[]) shou[2];
shou[0] = null;
}
return obj;
}
public boolean remove(Object obj) {
Object[] objs = shou;
while (true) {
if (obj.equals(objs[1])) {
break;
}
objs = (Object[]) objs[2];
if (objs == null) {
break;
}
}
if (objs == null) {
return false;
}
if (objs == shou) {
removeFirst();
} else if (objs == wei) {
removeLast();
} else {
Object[] shang = (Object[]) objs[0];
Object[] xia = (Object[]) objs[2];
shang[2] = xia;
xia[0] = shang;
}
return true;
}
private Object[] dq = null;
public boolean hashNext() {
if (dq == null) {
dq = shou;
if (dq == null) {
return false;
}
return true;
}
dq = (Object[]) dq[2];
if (dq == null) {
return false;
}
return true;
}
public Object Next() {
return dq[1];
}
}
测试类:
ackage com.linkes;
public class Test {
public static void main(String[] args) {
MyLinkeList linke = new MyLinkeList();
linke.add("a");
linke.addlast("b");
linke.addFirst("c");
linke.addFirst("d");
linke.addFirst("e");
linke.addFirst("f");
linke.addFirst("g");
linke.removeAll(1);
while(linke.hashNext()){
System.out.println(linke.Next());
}
}
}
|