删除元素思路:
- 寻找的应该是被删除元素B的前一个元素A
- 利用A的next直接指向C来进行删除B的操作
package com.ran;
public class hello {
public static void main(String[] args) {
HeroNode hero1=new HeroNode(1,"ran","qwe");
HeroNode hero2=new HeroNode(2,"rasd","asd");
HeroNode hero3=new HeroNode(3,"zxc","zxc");
HeroNode hero4=new HeroNode(4,"asdasd","fgh");
SingleLinkedList lianbiao=new SingleLinkedList();
lianbiao.add2(hero1);
lianbiao.add2(hero4);
lianbiao.add2(hero2);
lianbiao.add2(hero3);
lianbiao.shanchu(1);
lianbiao.list();
}
}
//定义一个SingleLinkedList 管理我们的英雄
class SingleLinkedList{
HeroNode head=new HeroNode(0,"","");
public void add(HeroNode heroNode){
HeroNode temp=head;
while (true){
if(temp.next==null){
break;
}
temp=temp.next;
}
temp.next=heroNode;
}
public void add2(HeroNode heroNode){
HeroNode temp=head;
boolean qwe=false;
while (true){
if (temp.next==null){
break;
}
if(temp.next.no>heroNode.no){
break;
}
else if(temp.next.no==heroNode.no){ //注意一下 都用temop.next.no判断
qwe=true;
break;
}
temp=temp.next;
}
if(qwe){
System.out.println("存在了添加不了");
}else {
heroNode.next=temp.next;
temp.next=heroNode;
}
}
public void shanchu(int no){
HeroNode temp=head;
boolean qqq=false;
if(head==null){
System.out.println("空");
}
while (true){
if(temp.next==null){
break;
}
if(temp.next.no==no){
qqq=true;
break;
}
temp=temp.next;
}
if(qqq){
temp.next=temp.next.next;
}
else {
System.out.println("meiyou zhaodao");
}
}
public void list(){
if(head.next==null){
System.out.println("kong");
return;
}
HeroNode temp=head;
while (true){
if(temp.next==null){
break;
}
System.out.println(temp.next);
temp=temp.next;
}
}
}
//定义一个heroNode,每一个heroNode对象就是一个节点
class HeroNode{
public int no;
public String name;
public String chuohao;
public HeroNode next;
public HeroNode(int no, String name, String chuohao) {
this.no = no;
this.name = name;
this.chuohao = chuohao;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", chuohao='" + chuohao + '\'' +
'}';
}
}
运行结果如下: