package com.dataconstructer.Linklist;
/**
-
@Author: fanfna
-
Date:Created in 22:24 2022/5/8
*/
public class SingleLinkedList {
public static void main(String[] args) {
HeroNode heroNode1 = new HeroNode(1,“宋江”, “及时雨”);
HeroNode heroNode2 = new HeroNode(2,“卢俊义”,“玉麒麟”);
HeroNode heroNode3 = new HeroNode(3,“吴用”,“智多星”);
SingleLinked singleLinked = new SingleLinked();
singleLinked.addByOrder(heroNode1);
singleLinked.addByOrder(heroNode2);
singleLinked.addByOrder(heroNode3);
singleLinked.list();
HeroNode newHeroNode = new HeroNode(2,“小路”,“小尾巴”);
singleLinked.update(newHeroNode);
singleLinked.list();//删除一个结点 singleLinked.delete(1); singleLinked.delete(2); singleLinked.delete(3); System.out.println("删除后链表"); singleLinked.list();
}
}
class SingleLinked{
private HeroNode head = new HeroNode(0,“”,“”);
/*从单链表中删除节点思路:辅助变量找到要删除的节点,根本无法删除- 所有只能先找到要删除的节点的前一个节点 temp
- 2,temp.next = temp.next.next
- 3,被删除的节点将不会有其它引用指向,会被GC回收*/
public void delete(int no){
HeroNode temp = head;
boolean flag = false;//表示是否找到待删除的节点的前一个节点
while (true){
if (temp.next == null){
break;//已经到链表最后
}
if (temp.next.no == no){
//找到了待删除节点的前一个结点 temp
flag = true;
break;
}
temp = temp.next;
}
//判断flag
if (flag){
temp.next = temp.next.next;
}else {
System.out.printf(“要删除的%d结点不存在”,no);
}
}
//修改节点的信息
/根据newHeroNode的no来修改/
public void update(HeroNode newHeroNode){
//判断是否为空
if (head.next == null){
System.out.println(“链表是空”);
return;
}
//找到修改的节点,根据No编号
HeroNode temp = head.next;
boolean flag = false;//表示是否找到该节点
while (true){
if (temp == null){
break;//到了链表最后
}
if (temp.no == newHeroNode.no){
//找到了修改节点
flag = true;
break;
}
temp = temp.next;
}
//根据flag判断是否找到要修改的节点
if (flag){
temp.name = newHeroNode.name;
temp.nickName = newHeroNode.nickName;
}else {
//没有找到
System.out.printf(“没有找到编号 %d的节点,不能修改\n”,newHeroNode.no);
}
}
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;//后移
}
//判断flag值
if (flag){
//不能添加
System.out.println(“准备插入的英雄已存在”);
}else {
//插入到链表中,temp的后面
heroNode.next = temp.next;
temp.next = heroNode;
}
}
public void add(HeroNode heroNode){
HeroNode temp = head;
while (true){
if (temp.next == null){
break;
}
temp = temp.next;
}
temp.next = heroNode;
}
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 hNo,String hName,String hnickName){
this.no = hNo;
this.name = hName;
this.nickName = hnickName;
}
@Override
public String toString() {
return “HeroNode{” +
“no=” + no +
“, name='” + name + ‘’’ +
“, nickName='” + nickName + ‘’'+
‘}’;
}
}