列表代码
class Lianbiao<E>{
private E data;
private Lianbiao<E> next;
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
public Lianbiao<E> next() {
return next;
}
public Lianbiao<E> getNext() {
return next;
}
public void setNext(Lianbiao<E> next) {
this.next = next;
}
/**
* 查询对应位置的数据
* @param index
* @return
*/
public E getIndex(int index){
if(index < 0){
throw new IndexOutOfBoundsException();
}
Lianbiao<E> temp = this.next();
for(int i = 1;i <= index;i++){
temp = temp.next();
if(temp == null){
throw new IndexOutOfBoundsException();
}
}
return temp.getData();
}
/**
* 添加数据
* @param data
* @return
*/
public Lianbiao<E> addData(E data){
Lianbiao<E> lb = new Lianbiao<E>();
lb.setData(data);
lb.setNext(this.next());
this.setNext(lb);
return lb;
}
/**
* 删除本节点之后第一个对应值
* @param data
* @return
*/
public boolean remove(E data){
Lianbiao<E> pre = this.findPre(data);
if(pre == null || pre.next() == null){
return false;
}else{
pre.setNext(pre.next().next());
return true;
}
}
/**
* 查找当前节点
* @param data
* @return
*/
public Lianbiao<E> find(E data){
Lianbiao<E> temp = this.next();
while(temp.getData() != data){
temp = temp.next();
if(temp == null){
return null;
}
}
return temp;
}
/**
* 查找父级
* @param data
* @return
*/
public Lianbiao<E> findPre(E data){
Lianbiao<E> pre = this;
Lianbiao<E> temp = this.next();
while(temp.getData() != data){
pre = temp;
temp = temp.next();
if(temp == null){
return null;
}
}
return pre;
}
@Override
public String toString() {
return "Lianbiao [data=" + data + ", next=" + next + "]";
}
}
测试代码
public static void main(String[] args) {
Lianbiao<Integer> lb = new Lianbiao<Integer>();
lb.addData(0).addData(1).addData(2).addData(4).addData(3);
// lb.addData(0).addData(1);
// lb.addData(0);
Lianbiao<Integer> temp = lb.next();
boolean b = lb.remove(4);
if(b){
System.out.println("成功");
}else{
System.out.println("失败");
}
// System.err.println(lb.getIndex(5));
while(temp != null){
System.out.println(temp.getData());
temp = temp.next();
}
System.out.println(lb.find(1));
}