web123456

Creation and traversal of Java single linked lists

package com.tentact.linkedlist; public class SingleLinkedList { public static void main(String[] args) { //Check the test //Create node first HeroNode hero1 = new HeroNode(1, "Song Jiang", "Timely Rain"); HeroNode hero2 = new HeroNode(2, "Lu Junyi", "Jade Qilin"); HeroNode hero3 = new HeroNode(3, "Wu Yong", "Smart Stars"); HeroNode hero4 = new HeroNode(4, "Lin Chong", "Leopard Head"); //Create a link to SingleLinkedList1 singleLinkedList = new SingleLinkedList1(); //join in singleLinkedList.add(hero1); singleLinkedList.add(hero2); singleLinkedList.add(hero3); singleLinkedList.add(hero4); //Show one singleLinkedList.list(); } } //Define SingleLinkedList to manage our heroes class SingleLinkedList1 { //Initialize a head node first, do not move the head node and do not store specific data. private HeroNode head = new HeroNode(0, "", ""); //Add node to one-way linked table //Idea, when the order of numbers is not considered. //1. Find the last node of the current linked list //2. Point the next of the last node to the new node public void add(HeroNode heroNode) { //Because the head node cannot move, we need an auxiliary traversal temp HeroNode temp = head; //Travel through the linked list and find the last node location while(true) { //Find the last of the linked list if(temp.next == null) { break; } //If the last is not found, move the temp back temp = temp.next; } //When exiting the while loop, temp points to the end of the linked list //Point the next of the last node to the new node temp.next = heroNode; } //Show the linked list [traversal] public void list() { //Judge whether the linked list is empty if(head.next == null) { System.out.println("Link list is empty"); return; } //Because the head node cannot move, we need an auxiliary variable to traverse it HeroNode temp = head.next; while(true) { //Judge whether it is at the end of the linked list if(temp == null) { break; } //Export node information System.out.println(temp); //Move temp backwards, be careful temp = temp.next; } } } //Define a HeroNode, each HeroNode object is a node 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; } @Override public String toString() { return "HeroNode [no=" + no + ", name=" + name + ", nickname=" + nickname +"]"; } //For display method, rewrite toString }