public class SingleLinkedListDemo {
public static void main(String[] args) {
Hero hero = new Hero(1, "lbl", "张三");
Hero hero1 = new Hero(2, "lbl222", "张三222");
Hero hero2 = new Hero(3, "lbl333", "张三333");
Hero hero3 = new Hero(4, "lbl333", "张三333");
Hero hero4 = new Hero(4, "lbl444", "张三444");
Hero hero5 = new Hero(5, "lbl444", "张三444");
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.addByOrder(hero3);
singleLinkedList.addByOrder(hero);
singleLinkedList.addByOrder(hero2);
singleLinkedList.addByOrder(hero1);
singleLinkedList.update(hero4);
singleLinkedList.update(hero5);
singleLinkedList.del(4);
singleLinkedList.findAll();
}
}
class SingleLinkedList{
//生成头节点
private Hero head=new Hero(0,"","");
//单向链表添加(错误)
// public void add(Hero hero){
// Hero temp=head.next;//错误原因,因为head只是没有具体值,而head.next为null,所以相当于Hero temp=null;导致temp与head没有关联
//
// while (true){
// if(temp==null){//所以一直进入这个条件里
// temp=hero;这里的temp与head没有了联系
// break;
// }
// temp=temp.next;
// }
// }
//单向链表添加(正确)
public void add(Hero hero){
Hero temp=head;
while (true){
if(temp.next==null){
temp.next=hero;//给头节点的Hero对象附上了值
break;
}
temp=temp.next;
}
}
//单项列表的顺序插入
public void addByOrder(Hero hero){
Hero temp=head;
while (true){
if(temp.next==null){
temp.next=hero;
break;
}
else if(temp.next.id>hero.id){
hero.next=temp.next;
temp.next=hero;
break;
}else if(temp.next.id==hero.id){
System.out.println("人物重复了");
break;
}
temp=temp.next;
}
}
//修改节点的信息,根据id号来改编
public void update(Hero hero){
Hero temp=head;
if (head.next==null){
System.out.println("这是空链表");
return;
}
while (true){
if(temp.next==null){
System.out.println("无这个人物");
break;
} else if(temp.next.id==hero.id){
temp.next.name=hero.name;
temp.next.nickName=hero.nickName;
break;
}
temp=temp.next;
}
}
//链表的删除
public void del(int id){
Hero temp=head;
if (head.next==null){
System.out.println("这是空链表");
return;
}
while (true){
if(temp.next==null){
System.out.println("无这个人物");
break;
}else if(temp.next.id==id){
if(temp.next.next==null){//这是temp.next为最后一个节点的情况
temp.next=null;
break;
}
temp.next=temp.next.next;
}
temp=temp.next;
}
}
//遍历单向链表
public void findAll(){
Hero temp=head.next;
if (head.next==null){
System.out.println("这是空链表");
return;
}
while (true){
if(temp==null){
break;
}
System.out.println(temp);
temp=temp.next;
}
}
}
class Hero{
public int id;
public String name;
public String nickName;
public Hero next;
public Hero(int id, String name, String nickName) {
this.id = id;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "Hero{" +
"id=" + id +
", name='" + name + '\'' +
", nickName='" + nickName + '\'' +
'}';
}
}
单链表增删改遍历
最新推荐文章于 2024-09-08 12:41:07 发布