package com.dai.linkedList; public class SingleLinkedListDemo { 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, "林冲", "豹子头"); SingleLinkedList singlelinkedList = new SingleLinkedList(); singlelinkedList.add(hero1); singlelinkedList.add(hero2); singlelinkedList.add(hero3); singlelinkedList.add(hero4); singlelinkedList.list(); } } //定义SingleLinkedList管理英雄 class SingleLinkedList{ //先初始化一个头结点 private HeroNode head = new HeroNode(0, "", ""); //添加节点到单向链表 public void add(HeroNode heroNode) { //当不考虑编号的顺序时,找到当前链表的最后节点,将最后节点的next指向新的节点就行 //头结点不能动,需要一个辅助 HeroNode temp = head; while(true) { if(temp.next == null) { break; } 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 no, String name, String nickname) { this.no = no; this.name = name; this.nickname = nickname; } //为了显示方便,重写toString 方法 @Override public String toString() { return "HeroNode [no=" + no + ", name=" + name + ", nickname=" + nickname + "]"; } }