链表是树和图的基础,通过链表可以实现很多功能,这里简单实现一个按顺序添加数据的功能
package com.page;
//利用单链表实现英雄人物的存储
//按照排名进行存储
//英雄人物有排名、名称和别名三个数据
public class SingleLinkedListDemo {
public static void main(String[] args) {
SingleHeroList hero=new SingleHeroList();
hero.addByOrder(new HeroList(1,"宋江","及时雨"));
hero.addByOrder(new HeroList(5,"关胜","大刀"));
hero.addByOrder(new HeroList(3,"吴用","智多星"));
hero.addByOrder(new HeroList(2,"卢俊义","玉麒麟 "));
hero.listHero();
System.out.println(hero.length());
System.out.println(hero.getHeroByNo(3));
}
}
//一个英雄的管理类,实现增删改查
class SingleHeroList{
private HeroList hero=new HeroList(0,"","");//作为头节点,只作为定位功能
//按照排名添加英雄
public void addByOrder(HeroList heroList){
HeroList temp=hero;
//通过循环遍历找到需要插入的位置
while(true){
//注意,这三个的顺序不能改变
if (temp.next==null){
break;
}
if (temp.next.no==heroList.no){//排名存在
throw new RuntimeException(heroList.no+"这个排名已存在");
}
if (heroList.no<temp.next.no){
break;
}
//向后移动一步
temp=temp.next;
}
heroList.next=temp.next;
temp.next=heroList;
}
//删除英雄,若需要删除特定排名的英雄不存在,则返回false
public boolean del(int no){
if (hero.next==null)
throw new RuntimeException("链表为空");
HeroList temp=hero;
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;
}
return flag;
}
//改变英雄信息
public void changeHero(HeroList heroList){
if (hero.next==null)
return;
HeroList temp=hero;
while (true){
if (temp.next==null){
throw new RuntimeException(heroList.no+"这个排名的英雄id不存在");
}
temp=temp.next;
if (temp.no==heroList.no){
temp.name= heroList.name;
temp.alias= heroList.alias;
break;
}
}
}
//遍历英雄
public void listHero(){
if (hero.next==null){
System.out.println("null");
}
HeroList temp=hero.next;
while(true){
if (temp==null)
break;
System.out.println(temp);
temp=temp.next;
}
}
//查看某排名的英雄,若存在返回英雄信息,反之返回null
public HeroList getHeroByNo(int no){
if (hero.next==null)
return null;
HeroList temp=hero.next;
while (true){
if (temp.next==null){
throw new RuntimeException(no+"这个排名的英雄不存在");
}
if (temp.no==no){
return temp;
}
temp=temp.next;
}
}
//返回有效节点的个数
public int length(){
int count=0;
HeroList temp=hero;
while (true){
if (temp.next==null)
return count;
count++;
temp=temp.next;
}
}
}
//一个英雄的类
class HeroList{
public int no;//排名
public String name;//姓名
public String alias;//别名
public HeroList next;//指向下一个英雄,实现链式结构
//构造方法
public HeroList(int no,String name,String alias){
this.no=no;
this.name=name;
this.alias=alias;
}
//打印
@Override
public String toString() {
return "HeroList{" +
"no=" + no +
", name='" + name + '\'' +
", alias='" + alias + '\'' +
'}';
}
}