单链表
一、链表结构
逻辑结构
二、添加
2.1直接添加到最后面
2.2找到某一位置添加=
2.3 删除
package com
.love
.xu
.linkedList
;
;
public class SingleLinkedList {
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("准备插入的英雄编号 %d 已经存在了,不能加了\n",heroNode
.no
);
}else {
heroNode
.next
= temp
.next
;
temp
.next
= heroNode
;
}
}
public void update(HeroNode heroNode
){
if(head
.next
== null
){
System
.out
.println("链表为空");
return;
}
HeroNode temp
= head
.next
;
boolean flag
= false;
while (true){
if(temp
== null
){
break;
}
if(temp
.no
== heroNode
.no
){
flag
= true;
break;
}
temp
= temp
.next
;
}
if(flag
){
temp
.name
= heroNode
.name
;
temp
.nickname
= heroNode
.nickname
;
}else {
System
.out
.printf("没有找到 编号 %d 的节点,不能修改",heroNode
.no
);
}
}
public void delete(int no
){
HeroNode temp
= head
;
boolean flag
= false;
while (true){
if(temp
== null
){
System
.out
.println("链表为空");
break;
}
if(temp
.next
.no
== no
){
flag
= true;
break;
}
temp
= temp
.next
;
}
if (flag
){
temp
.next
= temp
.next
.next
;
}else {
System
.out
.printf("没有找到 编号 %d 的节点,不能删除",no
);
}
}
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{
int no
;
String name
;
String nickname
;
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
+ '\'' +
'}';
}
}
转载请注明原文地址:https://tech.qufami.com/read-19535.html