定义节点数据结构
class HeroNode{
public int no;
public String name;
public String nickName;
public HeroNode next; //指向下一个node 默认为null
public HeroNode(int no,String name,String nickName){
this.no = no;
this.name = name;
this.nickName = nickName;
}
//重写toString()
}
实现链表
class SingleLinkedList{
private HeroNode head = new HeroNode(0,"",""); //初始化头节点
public HeroNode getHead() {
return head;
}
/*
* @param heroNode 要增加的节点对象
* @return
* */
public void add(HeroNode heroNode){
HeroNode temp = head;
while (true){
if (temp.next == null)
break;
temp = temp.next;
}
temp.next = heroNode;
}
/*
* @param heroNode 要按顺序增加的节点对象
* @return
* */
public void addByOrder(HeroNode heroNode){
HeroNode temp = head;
boolean flag = false; //标志添加的编号是否存在 默认false
while (true){
if (temp.next == null)
break;
if (temp.next.no > heroNode.no)
break;
else if (temp.next.no == heroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag)
System.out.println("准备插入的编号 " + heroNode.no + " 已经存在了");
else{
heroNode.next = temp.next;
temp.next = heroNode;
}
}
/*
* @param no 要删除节点的序号,避免空指针异常
* @return
* */
public void delete(int no){
if (head.next == null) {
System.out.println("链表为空");
return;
}
HeroNode temp = head;
boolean flag = false; //表示是否存在要删除的节点
while (true){
if (temp.next == null){
break;
}else if (temp.next.no == no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.next = temp.next.next;
}else {
System.out.println("准备删除的编号 " + no + " 不存在");
}
}
/*
* @param newHeroNode 修改后的新节点
* @return
* */
public void update(HeroNode newHeroNode){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
boolean flag = false; //表示是否存在要更新的节点
while (true){
if (temp == null)
break;
else if (temp.no == newHeroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.name = newHeroNode.name;
temp.nickName = newHeroNode.nickName;
}else {
System.out.println("准备修改的编号 " + newHeroNode.no + " 不存在");
}
}
//显示链表(遍历)
public void list(){
if (head.next == null){
System.out.println("链表为空");
return;
}
HeroNode temp = head.next;
while (true){
if (temp == null)
break;
System.out.println(temp);
temp = temp.next;
}
}
}