单链表的创建
public class LinkedListDemo {
public static void main(String[] args) {
HeroNode hero1 = new HeroNode(1, "张三", "小三");
HeroNode hero2 = new HeroNode(2, "李四", "小思");
HeroNode hero3 = new HeroNode(3, "王五", "小五");
LinkedList linkedList = new LinkedList();
linkedList.add(hero1);
linkedList.add(hero2);
linkedList.add(hero3);
linkedList.showList();
}
}
//管理英雄结点
class LinkedList{
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 showList()
{
//判断链表为空的方法,如果头结点的下一个为空,则链表为空
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;//这一行很重要,不然就是死循环
}
}
}
//定义heronode,每个heronode代表一个对象结点
class HeroNode{
private int no;
private String name;
private String nickname;
public 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 + '\'' +
'}';
}
}