单链表构造
每个节点可以存放到离散空间中,利用指针将每个节点串起来
节点由数据域与指针域组成,指针域只存在一个指针,指向下一个节点
存在一个头结点,无数据域,指针指向首节点,方便后续操作
Java中伪指针的表示——浅拷贝
类名 变量 = 对象名
这种不用new的实例化,让变量可以作为指针使用(内存地址相同),当变量(该变量可以看作一个对象)属性改变时,它指向的那个对象属性跟着改变
节点如何表示
class HeroNode {
public int id;
public String name;
public HeroNode next;
public HeroNode(int hid, String hname) {
this.id = hid;
this.name = hname;
}
public String print() {
return "HeroNode 英雄编号:" + id + "英雄姓名:" + name;
}
}
链表的整体架构
package 数据结构.单链表;
class HeroNode {
public int id;
public String name;
public HeroNode next;
public HeroNode(int hid, String hname) {
this.id = hid;
this.name = hname;
this.next = null;
}
@Override
public String toString() {
return "HeroNode 英雄编号: " + id + " 英雄姓名: " + name;
}
}
class HeroLink {
private HeroNode head = new HeroNode(0, "");
public void add(HeroNode heroNode) {
HeroNode temp = head;
while (true) {
if (temp.next == null) {
break;
} else {
temp = temp.next;
}
}
temp.next = heroNode;
}
public void list(){
if(head.next==null){
System.out.println("链表为空");
return;
}
HeroNode temp = head;
while (temp.next != null) {
temp = temp.next;
System.out.println(temp);
}
}
}
public class 单链表实现 {
public static void main(String[] args) {
HeroNode hero1 = new HeroNode(1,"宋江");
HeroNode hero2 = new HeroNode(2,"吴用");
HeroNode hero3 = new HeroNode(3,"林冲");
HeroNode hero4 = new HeroNode(4,"武松");
HeroLink heroLink = new HeroLink();
heroLink.add(hero1);
heroLink.list();
heroLink.add(hero2);
heroLink.add(hero3);
heroLink.add(hero4);
heroLink.list();
}
}
|