- 实现代码
实现代码
class SingleLinkedList{
//初始化头节点
private HeroNode head = new HeroNode(0,"","");
//在链表尾部添加节点
public void add(int no , String name, String nickname){
HeroNode cur = head ;
//令cur指向尾节点
while (cur.next != null){
cur = cur.next;
}
//此时cur指向尾节点,开始插入
HeroNode newNode = new HeroNode(no,name,nickname);
cur.next = newNode;
}
//通过编号插入,插入时会根据英雄的编号来插入
public void addByOrder(int no , String name, String nickname){
HeroNode newNode = new HeroNode(no,name,nickname);
//1.if list is null
if(null == head.next){
head.next = newNode;
}
//2. if list is not null
else{
//find appropriate location and insert
HeroNode cur = head;
while(null != cur.next){
if(newNode.no < cur.next.no){
//newNode.no比cur.next.no小,直接插入到cur后
newNode.next = cur.next;
cur.next = newNode;
//插入完成,返回
return ;
}
else if(newNode.no == cur.next.no){
System.out.println("该编号已存在,请重新插入!");
return ;
}
else{
//newNode.no不满足比cur.next.no小
//移动cur
cur = cur.next;
}
}
//此时cur指向尾节点,这时直接插入尾节点后面
cur.next = newNode;
}
}
//通过no来修改节点
public void update(int no , String name , String nickname){
//判断链表是否为空
if(null == head.next) {
System.out.println("链表为空!");
return;
}
//创建辅助节点cur
HeroNode cur = head.next;
//寻找cur.no == no的节点
while(null != cur){
//判断cur.no
if(cur.no == no){
//找到节点,修改name和nickname
cur.name = name;
cur.nickname = nickname;
return;
}
cur = cur.next;
}
System.out.println("您输入的编号有误,修改失败");
}
//删除节点
public void deleNode(int no){
//判断链表是否为空
if(null == head.next){
System.out.println("链表为空,删除失败");
return;
}
//创建辅助指针
HeroNode cur = head;
//遍历链表
while(null != cur.next){
if(cur.next.no == no){
//找到要删除的节点
cur.next = cur.next.next;
return;
}
cur = cur.next;
}
//遍历结束,没有找到要删除的节点
System.out.println("没有找到要删除的节点,删除失败!");
}
//遍历链表
public void traverse(){
//判断链表是否为空
if(null == head.next){
System.out.println("链表为空,遍历失败");
return;
}
//辅助指针
HeroNode cur = head.next;
while(null != cur){
System.out.println(cur);
cur = cur.next;
}
}
}
//定义HeroNode,每个HeroNode对象是一个节点
class HeroNode{
//成员属性
public int no;
public String name;
public String nickname;
public HeroNode next;//指向下一个节点
//构造器
public HeroNode(int no , String name , String nickname){
this.no = no;
this.name = name;
this.nickname = nickname;
this.next = null;
}
//为了显示方便,重写toString方法
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)