模拟LinkedList源码

复制代码
package com.msb.test04;

/**
 * @author : liu
 * 日期:08:19:35
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class Node {//节点类
    //三个属性
    //上一个元素的地址
    private Node pre;
    //当前存入的元素
    private Object obj;
    //下一个元素的地址
    private Node next;

    public Node getPre() {
        return pre;
    }

    public void setPre(Node pre) {
        this.pre = pre;
    }

    public Object getObj() {
        return obj;
    }

    public void setObj(Object obj) {
        this.obj = obj;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    @Override
    public String toString() {
        return "Node{" +
                "pre=" + pre +
                ", obj=" + obj +
                ", next=" + next +
                '}';
    }

}
复制代码
复制代码
package com.msb.test04;

/**
 * @author : liu
 * 日期:08:25:24
 * 描述:IntelliJ IDEA
 * 版本:1.0
 */
public class MyLinkedList {
    //链中一定有一个首节点:
    Node first;
    //链中一定有一个尾结点:
    Node last;
    //计数器:
    int count=0;
    //提供一个构造器
    public MyLinkedList(){
         }
    //添加元素方法:
    public void add(Object o){
        if(first==null){//证明你添加的元素是第一个节点
            //将添加的元素封装为一个对象
            Node n = new Node();
            n.setPre(null);
            n.setObj(o);
            n.setNext(null);
            //当前链中第一个节点变为n
            first=n;
            //当前链中最后一个节点变为n
            last=n;
        }else{//已经不是第一个节点了
            //
            Node n =new Node();
            n.setPre(last);//n的上一个节点,一定是当前链中的最后一个节点last
            n.setObj(o);
            n.setNext(null);
            //当前链中的最后一个节点的下一个元素要指向n
            last.setNext(n);
            //将最后一个节点变为n
            last=n;
        }
        //链中元素数量加1
        count++;
    }
    //得到集合中元素的数量
    public int getSize(){
        return count;
    }
    //通过下标获得元素
    public Object get(int index){
        //获取链表的头元素
        Node n=first;
        //一路next得到想要的元素
        for (int i = 0; i < index; i++) {
            n = n.getNext();
        }
        return n.getObj();
    }
}
class Test{
    //这是一个main方法:是程序的入口
    public static void main(String[] args) {
        //创建一个集合对象
        MyLinkedList ml=new MyLinkedList();
        ml.add("aa");
        ml.add("bb");
        ml.add("cc");
        System.out.println(ml.getSize());
        System.out.println(ml.get(2));
    }
}
复制代码

 

Debug验证数据添加成功

 

posted @   爱的加勒比  阅读(21)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示