- 链表是以节点的方式来存储,是链式存储,是有序的列表
- 每个节点包含data域,next域:指向下一个节点
- 链表的各个节点不一定是连续存储
- 链表分带头节点的链表和没有头节点的链表
内存图
逻辑图
class SingerLinkedList {
//初始化头节点,头节点不能动,不存放具体的数据
Hero head = new Hero(0, "");
public void add(Hero hero) {
//定义辅助节点
Hero temp = head;
while (true) {
if (temp.next == null) {
temp.next = hero;
break;
}
temp = temp.next;
}
}
//根据no从小到大排序添加节点
public void addOrder(Hero hero) {
//定义辅助节点 头节点不能动
Hero temp = head;
while (true) {
if (temp.next == null) {
temp.next = hero;
break;
}
if (temp.no < hero.no && temp.next.no > hero.no) {
hero.next = temp.next;
temp.next = hero;
break;
}
if(temp.no == hero.no || temp.next.no == hero.no){
System.out.println("链表中有此序号"+hero);
break;
}
temp = temp.next;
}
}
public void show() {
//判断链表是否为空
if (head.next == null) {
System.out.println("链表为空");
return;
}
Hero temp = head.next;
while (true) {
if (temp == null) {
break;
}
System.out.println(temp);
temp = temp.next;
}
}
public void update(Hero hero){
Hero temp = head;
//修改节点信息,根据no编号修改,no编号不能改
while (true){
if(temp.no == hero.no){
temp.name = hero.name;
break;
}
if(temp.next == null){
System.out.println("没有此节点,请先添加~~");
break;
}
temp = temp.next;
}
}
public void remove(int no){
Hero temp = head.next;
while (true){
if(temp.no == no){
temp.next = temp.next.next;
break;
}
if(temp.next == null){
System.out.println("没有找到此序号的链表");
break;
}
temp = temp.next;
}
}
}
public class Hero {
public Integer no;
public String name;
public Hero next;
public Hero(Integer no, String name) {
this.no = no;
this.name = name;
}
@Override
public String toString() {
return "Hero{" +
"no=" + no +
", name='" + name + '\'' +
", next=" + next +
'}';
}
}