愤怒中的小草

博客园 首页 新随笔 联系 订阅 管理
public class Element {
public Object object;
public Element next = null;

public Element(Object object){
this.object = object;
}
}
public class SingleLinkList {
private Element element;

public void init(){
element = new Element(null);
element.next = null;
}

public void add(int data){
Element node = new Element(data);
Element tmp = element;
while (tmp.next != null){
tmp=tmp.next;
}
tmp.next = node;
}

public void delete(Object value){
Element tmp = element;
//找到删除元素的上一个节点,在进行删除
while (tmp.next.object != value){
tmp = tmp.next;
}
tmp.next = tmp.next.next;
//删除的是下一个节点
/*while (tmp.next != null){
if(tmp.object == value){
tmp.next = tmp.next.next;
return;
}
tmp = tmp.next;
}*/
}

public int length(){
Element tmp = element;
int i=0;
while (tmp.next != null){
tmp = tmp.next;
i++;
}
return i;
}

public void display(){
Element tmp = element.next;
while (tmp != null){
System.out.println("链表的值:" + tmp.object);
tmp = tmp.next;
}
}
}
public class Demo {
public static void main(String[] args){
SingleLinkList sll = new SingleLinkList();
sll.init();
sll.add(1);
sll.add(2);
sll.add(3);
sll.add(4);
sll.add(5);
sll.display();
System.out.println("链表的长度为:" + sll.length());
System.out.println("---------------删除元素----------------------");
sll.delete(2);
sll.display();
System.out.println("链表的长度为:" + sll.length());
}
}

 

posted on 2019-04-23 23:09  愤怒中的小草  阅读(89)  评论(0编辑  收藏  举报