双向链表模拟

LinkedList底层结构

LinkedList的全面说明

  1. LinkedList底层实现了双向链表和双端队列特点
  2. 可以添加任意元素(元素可以重复),包括null
  3. 线程不安全,没有实现同步

LinkedList的底层操作机制

  1. LinkedList底层维护了一个双向链表.
  2. LinkedList中维护了两个属性first和last分别指向首节点和尾节点
  3. 每个节点(Node对象),里面又维护了prev、next、item三个属性,其中通过prev指向前一个,通过next指向后一个节点。最终实现双向链表.
  4. 所以LinkedList的元素的添加和删除,不是通过数组完成的,相对来说效率较高。
  5. 模拟一个简单的双向链表
public class LinkedList01 {
    public static void main(String[] args) {
        //模拟一个简单的双向链表

        Node jack = new Node("jack");
        Node tom = new Node("tom");
        Node wsh = new Node("wsh");

        //连接三个结点,形成双向链表
        //jack -> tom -> wsh
        jack.next = tom;
        tom.next = wsh;

        //wsh -> tom -> jack
        wsh.pre = tom;
        tom.pre = jack;

        Node first = jack; // 让first引用指向jack,就是双向链表的头结点
        Node last = wsh; // 让last引用指向wsh,就是双向链表的尾结点

        //从头到尾进行遍历
        System.out.println("===从头到尾进行遍历===");
        while (true){
            if(first == null){
                break;
            }
            //输出first信息
            System.out.println(first);
            first = first.next;
        }

        //从尾到头的遍历
        System.out.println("====从尾到头的遍历====");
        while (true){
            if(last == null){
                break;
            }
            //输出first信息
            System.out.println(last);
            last = last.pre;
        }

        //链表的添加对象/数据是很方便的
        //要求,是在tom---wsh之间,插入一个对象smith
        Node smith = new Node("smith");

        //下面就把smith加入到双向链表中
        tom.next = smith;
        smith.next = wsh;
        wsh.pre = smith;
        smith.pre = tom;

        //让first再次指向jack
        first = jack;

        //从头到尾进行遍历
        System.out.println("===从头到尾进行遍历===");
        while (true){
            if(first == null){
                break;
            }
            //输出first信息
            System.out.println(first);
            first = first.next;
        }

        //让last再次指向tom
        last = wsh;

        //从尾到头的遍历
        System.out.println("====从尾到头的遍历====");
        while (true){
            if(last == null){
                break;
            }
            //输出first信息
            System.out.println(last);
            last = last.pre;
        }

    }
}

//定义一个Node类,Node对象表示双向链表的一个结点
class Node{
    public Object item;//真正存放数据
    public Node next;//指向后一个结点
    public Node pre;//指向前一个结点

    public Node(Object name) {
        this.item = name;
    }

    @Override
    public String toString() {
        return "Node name = " + item;
    }
}
posted @   摘星丶仙  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示