package jiegou;
import java.util.List;
// 单链表
public class SingleLinkDemo {
public static void main(String[] args) {
HeroNode heroNode1 = new HeroNode(1, "松江", "及时雨");
HeroNode heroNode2 = new HeroNode(2, "吴用", "智多星");
HeroNode heroNode3 = new HeroNode(3, "林冲", "豹子头");
SingleLinkList linkList = new SingleLinkList();
linkList.add(heroNode1);
linkList.add(heroNode2);
linkList.add(heroNode3);
linkList.list();
}
}
// 链表管理节点
class SingleLinkList {
// 初始化一个头节点
private HeroNode head = new HeroNode(0, "", "");
// 添加节点到单向链表
public void add(HeroNode heroNode) {
// 找到链表最后
//将最后节点的 next 指向这个新节点
HeroNode temp = head;
//遍历链表
while (true) {
// 当 temp.next== null
if (temp.next == null) {
break;
}
// 没有找到最后 temp 后移
temp = temp.next;
}
temp.next = heroNode;
}
// 显示链表
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 {
public int no;
public String name;
public String nickname;
public HeroNode next; //指向下一个节点
// 构造方法
public HeroNode(int hNo, String HName, String HNickName) {
this.no = hNo;
this.name = HName;
this.nickname = HNickName;
}
@Override
public String toString() {
return "HeroNode{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}