1.分析
2.代码
package com.atguigu.linkedlist;
public class SingleLinkedListDemo {
public static void main(String[] args) {
HeroNode hero1 = new HeroNode(1,"松江1","及时雨1");
HeroNode hero2 = new HeroNode(2,"松江2","及时雨2");
HeroNode hero3 = new HeroNode(3,"松江3","及时雨3");
HeroNode hero4 = new HeroNode(4,"松江4","及时雨4");
SigleLinkedList sigleLinkedList = new SigleLinkedList();
sigleLinkedList.add(hero1);
sigleLinkedList.add(hero2);
sigleLinkedList.add(hero3);
sigleLinkedList.add(hero4);
sigleLinkedList.list();
SigleLinkedList sigleLinkedList2 = new SigleLinkedList();
sigleLinkedList2.addByOrder(hero1);
sigleLinkedList2.addByOrder(hero4);
sigleLinkedList2.addByOrder(hero3);
sigleLinkedList2.addByOrder(hero2);
sigleLinkedList2.list();
HeroNode newHeroNode = new HeroNode(2,"松江22","及时雨22");
sigleLinkedList2.update(newHeroNode);
sigleLinkedList2.list();
sigleLinkedList2.del(1);
}
}
class SigleLinkedList{
private 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 addByOrder(HeroNode heroNode){
HeroNode temp = head;
boolean flag = 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.printf("准备插入的英雄的编号已存在,不能加入\n",heroNode.no);
} else {
heroNode.next = temp.next;
temp.next = heroNode;
}
}
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;
}
if (temp.no == newHeroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.name = newHeroNode.name;
temp.nickname = newHeroNode.nickname;
}else {
System.out.printf("没有找到编号 %d 的节点",newHeroNode.no);
}
}
public void del(int no){
HeroNode temp = head;
boolean flag = false;
while (true){
if (temp.next == null){
break;
}
if (temp.next.no == no){
flag = true;
break;
}
temp = temp.next;
}
if (flag){
temp.next = temp.next.next;
}else {
System.out.println("要删除的节点不存在");
}
}
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;
}
}
}
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;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
|