public class单向链表 {public static voidmain(String[] args) {
HeroNode name1=new HeroNode(1,"小袁","世界上最帅的男人");
HeroNode name2=new HeroNode(2,"xx","xx");
HeroNode name3=new HeroNode(3,"ww","ww");
HeroNode name4=new HeroNode(4,"vv","xx");
SingleLinkedList singleLinkedList=newSingleLinkedList();
singleLinkedList.add1(name1);
singleLinkedList.add1(name4);
singleLinkedList.add1(name3);
singleLinkedList.add1(name2);
singleLinkedList.list();
System.out.println("修改后---------------");
HeroNode n=new HeroNode(2,"bb","bb");
singleLinkedList.update(n);
singleLinkedList.list();
System.out.println("删除后--------------");
singleLinkedList.delete(2);
singleLinkedList.list();
}
}//管理信息
classSingleLinkedList{//定义头节点,不存放具体数据
private HeroNode head=new HeroNode(0,"","");//定义按顺序添加方法
public voidadd1(HeroNode heroNode){//定义辅助变量
HeroNode temp=head;//定义标志
boolean flag=false;while (true){if(temp.next==null){break;
}if(temp.next.SerialNumber>heroNode.SerialNumber){//说明位置找到,在temp后面插入
break;
}else if(temp.next.SerialNumber==heroNode.SerialNumber){//说明添加信息已存在
flag=true;
}//后移遍历链表
temp=temp.next;
}if(flag){
System.out.println("信息已存在");
}else{//插入到链表
heroNode.next=temp.next;
temp.next=heroNode;
}
}//定义修改节点方法
public voidupdate(HeroNode newHeroNode){if(head.next==null){
System.out.println("链表为空");return;
}//定义辅助变量
HeroNode temp=head.next;//定义标志
boolean flag=false;while (true) {if (temp.next == null) {break;
}if(temp.SerialNumber==newHeroNode.SerialNumber){
flag=true;break;
}
temp=temp.next;
}if(flag){
temp.name=newHeroNode.name;
temp.information=newHeroNode.information;
}else{
System.out.println("没有找到");
}
}//定义删除方法
public void delete(intSerialNumber){
HeroNode temp=head;boolean flag=false;while (true){if(temp.next==null){break;
}if(temp.next.SerialNumber==SerialNumber){
flag=true;break;
}
temp=temp.next;
}if(flag){
temp.next=temp.next.next;
}
}//遍历
public voidlist(){//判断链表是否为空
if(head.next==null){
System.out.println("链表为空");return;
}//定义辅助变量
HeroNode temp=head.next;while (true){//判断是否到链表最后
if(temp==null){break;
}
System.out.println(temp);//将temp后移,不然会死循环
temp=temp.next;
}
}
}classHeroNode{public intSerialNumber;publicString name;publicString information;//指向下一个节点
publicHeroNode next;public HeroNode(intSerialNumber,String name,String information){this.SerialNumber=SerialNumber;this.name=name;this.information=information;
}
@OverridepublicString toString() {return "HeroNode{" +
"SerialNumber=" + SerialNumber +
", name='" + name + '\'' +
", information='" + information + '\'';
}
}