美文网首页
单链表的创建和遍历(自动排序版)

单链表的创建和遍历(自动排序版)

作者: YAOPRINCESS | 来源:发表于2020-07-02 00:07 被阅读0次

先上结果


image.png

package com.nan;

/**
 * @author klr
 * @create 2020-07-01-23:07
 */
public class SingleLinkedListDemo {

    public static void main(String[] args) {
        HeroNode hero1 = new HeroNode(1, "宋江", "及时雨");
        HeroNode hero2 = new HeroNode(5, "卢俊义", "玉麒麟");
        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();
    }
}

class SingleLinkedList{

    //头结点,不能动,不存放具体的数据
    private HeroNode head = new HeroNode(0,"","");


    //找到当前链表的最后结点
    //将最后这个结点的next指向新的结点
    public void add(HeroNode heroNode){
        //因为head结点不动,我们需要定义一个零时结点
        HeroNode temp = head;
        //遍历这个链表,找到最后
        while (true) {
            //列表为空,直接添加
            if (temp.next == null) {
                temp.next = heroNode;
                break;
            }
            //比较大小,直接插入
            if (temp.number <= heroNode.number && heroNode.number <= temp.next.number) {
                heroNode.next = temp.next;
                temp.next = heroNode;
                break;
            }
            //如果没有找到,就继续找
            temp = temp.next;
        }
    }

    //遍历
    public void list(){
        //判断链表是否为空
        if (head.next == null) {
            System.out.println("链表为空");
            return;
        }
        //因为head不能动
        HeroNode temp = head.next;
        while (true) {
            //判断是否到链表最后
            if (temp == null) {
                break;
            }
            //输出结点信息
            System.out.println(temp);
            //将temp后移
            temp = temp.next;
        }
    }
}

class HeroNode {
    public int number;//排名
    public String name;//姓名
    public String nickName;//绰号
    public HeroNode next;//指针

    public HeroNode(int number, String name, String nickName) {
        this.number = number;
        this.name = name;
        this.nickName = nickName;
    }

    @Override
    public String toString() {
        return "HeroNode{" +
                "number=" + number +
                ", name='" + name + '\'' +
                ", nickName='" + nickName +
                '}';
    }
}

相关文章

网友评论

      本文标题:单链表的创建和遍历(自动排序版)

      本文链接:https://www.haomeiwen.com/subject/ztnkqktx.html