单链表的创建及实现
作者:互联网
代码如下:
package com.liu.pro; public class ChainTable01 { public static void main(String[] args) { HeroNode heroNode1 = new HeroNode(1, "宋江", "及时雨"); HeroNode heroNode2 = new HeroNode(2, "吴用", "智多星"); HeroNode heroNode3 = new HeroNode(3, "林冲", "豹子头"); HeroNode heroNode4 = new HeroNode(4, "卢俊义", "玉麒麟"); LinkedList linkedList = new LinkedList(); linkedList.add(heroNode1); linkedList.add(heroNode2); linkedList.add(heroNode3); linkedList.add(heroNode4); linkedList.getLinkedList(); } } //创建链表 class LinkedList{ // 创建头节点 private HeroNode head = new HeroNode(); // 增加数据 public void add(HeroNode heroNode){ // 定义一个临时的变量 HeroNode temp = head; // 定义死循环,找到最后的节点 while (true){ if (temp.next == null){ // 退出循环 break; } // 后移 temp = temp.next; } // 找到最后一个节点后,将数据进行添加 temp.next = heroNode; } // 遍历链表数据 public void getLinkedList(){ HeroNode temp = head.next; if (temp.next == null) { System.out.println("链表为空"); } // 遍历并且打印链表 while (true){ // 链表的终点 if (temp == null) { break; } System.out.println(temp); // 后移 temp = temp.next; } } } //创建英雄类(链表的每一个数据块) class HeroNode{ private int no; private String name; private String nickName; public HeroNode next; //无参构造 public HeroNode() { } //有参构造 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 + '\'' + '}'; } }
测试结果:
标签:单链,String,temp,实现,创建,HeroNode,next,链表,public 来源: https://www.cnblogs.com/lhr123/p/16462276.html