Java单链表和LinkedList的实现

一、单链表的实现

                无头单向非循环链表

定义异常用于判断所给位置是否合法

public class IndexNotLegal extends RuntimeException{
   public IndexNotLegal(){

   }
   public IndexNotLegal(String smg){
       super(smg);
   }
}

class ListNode中包含当前节点的值和下一个节点指向 

实现链表的头插,尾插,任意位置插入,查找,删除一个节点,打印,计数,清空 

import java.util.List;

public class MySingleList {
    //节点
    class ListNode{
        public int val;
        public ListNode next;

        public ListNode(int val){
            this.val = val;
            next = null;
        }
    }

    public ListNode head;//代表链表的头结点
    //打印
    public void display(){
        ListNode cur = head;
        while(cur!=null){
            System.out.print(cur.val+"->");
            cur = cur.next;
        }
        System.out.println();
    }
    //节点个数
    public int size(){
        int count = 0;
        ListNode cur = head;
        while(cur!=null){
            count++;
            cur = cur.next;
        }
        return count;
    }

    //头插
    public void addFirst(int data){
        ListNode node = new ListNode(data);
        node.next = head;
        head = node;
 }

 //尾插法
    public void addLast(int data){
        ListNode node = new ListNode(data);
        if(head==null){
            head = node;
            return;
        }
        ListNode tail = head;
        while(tail.next != null){
            tail=tail.next;
        }
        tail.next = node;
  }

  //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index,int data){
        //判断合不合法
        try {
            checkIndex(index);
        }catch(IndexNotLegal e){
            e.printStackTrace();
        }

        if(index==0){
            addFirst(data);
            return;
        }
        if(index == size()){
            addLast(data);
            return;
        }
        ListNode cur = findIndexSubOne(index);
        ListNode node = new ListNode(data);
        node.next = cur.next;
        cur.next = node;
    }
    private void checkIndex(int index) throws IndexNotLegal{
        if(index<0||index>size()){
            throw new IndexNotLegal("index不合法");
        }
    }
    public ListNode findIndexSubOne(int index){
        ListNode cur = head;
        int count =0;
        while(count!=index-1){
            cur = cur.next;
            count++;
        }
        return cur;
    }
 //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key){
        ListNode cur = head;
        while(cur!=null){
            if(cur.val==key){
                return true;
            }
            cur = cur.next;
        }
        return false;
 }
 //删除出现关键字为key的节点
    public void remove(int key){
        if(head==null){
            return;
        }
        ListNode del = head;
        ListNode pre = head;
        while(del!=null){
            if(del.val==key){
                pre.next = del.next;
                del = del.next;
            }else{
            pre = del;
            del = del.next;
            }
        }
        if(head.val==key){
            head = head.next;
            return;
        }//最后判断头结点
 }

 public void clear(){
        ListNode cur = head;
        while(cur!=null){
            ListNode curN = cur.next;
            cur.next = null;
            cur = curN;
        }
        head = null;
 }
}

二、LinkedList

1、介绍

LinkedList的底层是双向链表结构,由于链表没有将元素存储在连续的空间中,元素存储在单独的节点中,然后通过引用将节点连接起来了,因此在任意位置插入或者删除元素时,不需要搬移元素,效率比较高。

        LinkedList实现了List接口

        LinkedList的底层使用了双向链表

        LinkedList没有实现RandomAccess接口,因此LinkedList不支持随机访问

        LinkedList的任意位置插入和删除元素时效率比较高,时间复杂度为O(1)

        LinkedList比较适合任意位置插入的场景

2、方法介绍

        add

直接增加

插入到指定位置

 addAll:尾插c 中的所有元素

         remove

删除 index 位置元素

删除遇到的第一个 o

 get:获取下标 index 位置元素

set:将下标 index 位置元素设置为 element

clear:清空

contains:判断 o 是否在线性表中

indexOf:返回第一个 o 所在下标

lastIndexOf:返回最后一个 o 的下标

subList:截取部分 list

三、LinkedList遍历方法

public static void main1(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        list.add(1);
        list.add(2);
        list.add(1,3);

        System.out.println(list);//直接打印
        System.out.println("==============");
        
        //foreach遍历
        for(Integer x: list){
            System.out.print(x+" ");
        }
        System.out.println();
        System.out.println("============");

        //for遍历
        int size = list.size();
        for (int i = 0; i < size; i++) {
            System.out.print(list.get(i)+" ");
        }
        System.out.println();
        System.out.println("============");
        
         //使用迭代器遍历-正向遍历
        Iterator<Integer> it = list.iterator();
        while(it.hasNext()){
            System.out.print(it.next()+" ");
        }
        System.out.println();
        System.out.println("============");

        Iterator<Integer> it2 = list.listIterator();
        while(it2.hasNext()){
            System.out.print(it2.next()+" ");
        }
        System.out.println();
        System.out.println("============");

        //使用迭代器遍历-反向遍历
        ListIterator<Integer> it3 = list.listIterator(list.size());
        while(it3.hasPrevious()){
            System.out.print(it3.previous()+" ");
        }
        System.out.println();
        System.out.println("============");
    }

 

 四、实现MyLikedList

        无头双向链表

定义异常用于判断所给位置是否合法

public class IndexNotIllegal extends RuntimeException{
    public IndexNotIllegal(){

    }
    public IndexNotIllegal(String smg){
        super(smg);
    }
}

方法实现 

public class MyLinkedList {
    static class ListNode{
        public int val;
        public ListNode prev;
        public ListNode next;

        public ListNode(int val){
            this.val = val;
        }
    }
    public ListNode head;//头结点
    public ListNode last;//尾节点

    public int size(){
        int size = 0;
        ListNode cur = head;
        while(cur!=null){
            size++;
            cur = cur.next;
        }
        return size;
    }
    public void display(){
        ListNode cur = head;
        while(cur!=null){
            System.out.print(cur.val+" ");
            cur = cur.next;
        }
        System.out.println();
    }
    public boolean contains(int key){
        ListNode cur = head;
        while(cur!=null){
           if(cur.val==key){
               return true;
           }
            cur = cur.next;
        }
        return false;
    }
    //头插法
    public void addFirst(int data){
        ListNode Node = new ListNode(data);
        if(head==null){
            head = last = Node;
        }else{
        Node.next = head;
        head.prev = Node;
        head = Node;
        }
    }
    //尾插法
    public void addLast(int data){
        ListNode Node = new ListNode(data);
        if(head==null){
            head = last = Node;
        }else{
            last.next = Node;
            Node.prev = last;
            last = Node;
        }
    }
    //任意位置插入,第一个数据节点为0号下标
    public void addIndex(int index,int data){
        try{
            checkIndex(index);
        }catch(RuntimeException e){
            e.printStackTrace();
        }
        if(index == 0){
            addFirst(data);
            return;
        }
        if(index == size()){
            addLast(data);
            return;
        }
        ListNode cur = findIndex(index);
        ListNode node = new ListNode(data);
        node.prev = cur.prev;
        node.next = cur;
        cur.prev.next = node;
        cur.prev = node;

    }
    private ListNode findIndex(int index){
        ListNode cur = head;
        while(index!=0){
            cur = cur.next;
            index--;
        }
        return cur;
    }
    public void checkIndex(int index)throws IndexNotIllegal{
        if(index<0||index>size()){
            throw new IndexNotIllegal("数组下标不合法");
        }
    }
    //删除第一次出现关键字为key的节点
    public void remove(int key){
        ListNode cur = head;
        while(cur!=null){
            if(cur.val==key) {
                if (cur == head) {
                    //处理头节点
                    head = head.next;
                    if(head != null){
                        head.prev = null;
                    }else{
                        last = null;
                    }
                } else {
                    if (cur.next == null) {
                        //处理尾节点
                        cur.prev.next = cur.next;
                        last = last.prev;
                    } else {
                        cur.prev.next = cur.next;
                        cur.next.prev = cur.prev;
                    }
                }
                return;//删完一个就跳出
            }
            cur = cur.next;
            }
    }

    //删除所有值为key的节点
    public void removeAllKey(int key){
        ListNode cur = head;
        while(cur!=null){
            if(cur.val==key) {
                if (cur == head) {
                    //处理头节点
                    head = head.next;
                    if(head != null){
                        head.prev = null;
                    }else{
                        last = null;
                    }
                } else {
                    if (cur.next == null) {
                        //处理尾节点
                        cur.prev.next = cur.next;
                        last = last.prev;
                    } else {
                        cur.prev.next = cur.next;
                        cur.next.prev = cur.prev;
                    }
                }
            }
            cur = cur.next;
        }
    }
    //得到单链表的长度
    public void clear(){
        ListNode cur = head;
        while(cur!=null){
            ListNode curN = cur.next;
            cur.next = null;
            cur.prev = null;
            cur = curN;
        }
        head = last = null;
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/525058.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

阿里云2024年优惠券领取及使用常见问题

阿里云是阿里巴巴旗下云计算品牌&#xff0c;服务涵盖云服务器、云数据库、云存储、域名注册等全方位云服务和各行业解决方案。为了吸引用户上云&#xff0c;阿里云经常推出各种优惠活动&#xff0c;其中就包括阿里云优惠券。本文将对阿里云优惠券领取及使用常见问题进行解答&a…

鸿蒙原生应用已超4000个!

鸿蒙原生应用已超4000个&#xff01; 来自 HarmonyOS 微博近期消息&#xff0c;#鸿蒙千帆起# 重大里程碑&#xff01;目前已有超4000个应用加入鸿蒙生态。从今年1月18日华为宣布首批200多家应用厂商正在加速开发鸿蒙原生应用&#xff0c;到3月底超4000个应用&#xff0c;短短…

DSOX3034T是德科技DSOX3034T示波器

181/2461/8938产品概述&#xff1a; 特点: 带宽:350 MHz频道:4存储深度:4 Mpts采样速率:5 GSa/s更新速率:每秒1000000个波形波形数学和FFT自动探测接口用于连接、存储设备和打印的USB主机和设备端口 触摸: 8.5英寸电容式触摸屏专为触摸界面设计 发现: 业界最快的无损波形更…

工业视觉检测

目录 我对工业视觉检测的了解 一、关键组成部分 二、应用场景 三、技术挑战 我对工业视觉检测的了解 工业视觉检测是利用机器视觉技术对产品质量进行自动化检查的过程&#xff0c;它在制造业中扮演着至关重要的角色&#xff0c;用于确保产品质量、提高生产效率、减少人工成…

小核引导RTOS---RISC-V C906

文章目录 参考日志编译框架目标fip 启动流程fip文件组成BL2程序 总结思考备注 参考 参考1. How does FSBL load the FreeRTOS on the small core and execute it?参考2. Duo now supports big and little cores?Come and play!Milk-V Duo, start&#xff01;参考3. 使用uboo…

ES学习笔记01

1.ES安装 下载地址&#xff1a; es官网下载 这里使用的是7.8.0的版本信息 下载完成后解压即可完成安装 2.启动运行 点击bin目录下的elasticsearch.bat文件即可启动 在浏览器中输入localhost:9200显示如下&#xff1a; 在路径中加入对应访问后缀即可访问对应信息 如&#…

【学习】移动端App性能测试流程有哪些

移动端App性能测试是保证App性能表现的重要环节之一。随着移动设备的普及和移动互联网的发展&#xff0c;移动端App的性能测试变得越来越重要&#xff0c;通过科学合理的性能测试可以发现并解决潜在的性能问题优化App运行效果提高用户体验。性能测试旨在评估App在各种场景下的性…

板材的加强筋优化-abaqus操作过程

前言 本示例详细讲解使用abaqus实现板材的加强筋优化的操作过程。 本页讨论 前言一、创建模型1.创建几何部件2.定义材料属性3.创建装配实体4.创建分析步5.创建边界条件及载荷6.划分网格7.创建分析作业并提交分析8.可视化后处理 二、设置优化1.创建优化任务2.创建设计响应3.创…

嵌入式软件工程师如何提高技术深度?

构建坚实且深厚的技术根基&#xff0c;其重要程度可谓举足轻重。唯有在对基础知识进行深入探究和理解的前提之下&#xff0c;方能够在理论的指引之下&#xff0c;持续地深入以及拓展技术领域。倘若缺乏稳固坚实的基础&#xff0c;那么深入开展研究便无从谈起。 在强调技术深度…

说说 HTTP1.0/1.1/2.0 的区别?

文章目录 一、HTTP1.0二、HTTP1.1三、HTTP2.0多路复用二进制分帧首部压缩 四、总结参考文献 一、HTTP1.0 HTTP协议的第二个版本&#xff0c;第一个在通讯中指定版本号的HTTP协议版本 HTTP 1.0 浏览器与服务器只保持短暂的连接&#xff0c;每次请求都需要与服务器建立一个TCP连…

bin、hex、exe、elf文件类型到底有何区别?如何解读hex文件和elf文件?...相关内容都在这里!

《嵌入式工程师自我修养/C语言》系列——bin、hex、exe、elf文件类型到底有何区别&#xff1f;readelf用法全面解读&#xff01; 一、常见文件类型之&#xff1a;bin、hex、elf、exe1.1 bin、hex、exe、elf文件类型到底有何区别&#xff1f;1.2 如何读懂一份hex文件&#xff1f…

数字人解决方案——Wav2lip本地部署

1、安装anaconda anaconda自行下载安装 2、下载wav2lip 在github中搜索wav2lip ​ git clone https://github.com/Rudrabha/Wav2Lip.git ​ 源码到本地 准备脸部检测预训练模型 下载地址&#xff1a;https://www.adrianbulat.com/downloads/python-fan/s3fd-619a316812…

安卓远离手机app

软件介绍 远离手机是专门为防止年轻人上瘾而打造的生活管理类的软件,适度用手机&#xff0c;保护眼睛&#xff0c;节约时间。 下载 安卓远离手机app

C++ 一种简单的软件验证码 程序授权使用 收费付费使用 无需注册 用机器码得到一个加密值 再对比加密值是否一致 只需加密

简单软件授权方案 1、获取机器码&#xff0c;发给软件开发者 2、开发者用机器码加密得到一个密文 发给使用者 3、使用者 用这个密文 与本地计算密文比较密文是否一致&#xff0c;一致就把密文写入到注册表&#xff0c;下次登录从注册表读密文对比。 &#xff08;最重要的是密…

【C++】STL学习之string的使用

&#x1f525;博客主页&#xff1a; 小羊失眠啦. &#x1f3a5;系列专栏&#xff1a;《C语言》 《数据结构》 《C》 《Linux》 《Cpolar》 ❤️感谢大家点赞&#x1f44d;收藏⭐评论✍️ 文章目录 前言一、basic_string二、编码理解三、构造函数相关3.1 无参(默认)构造函数3.2 …

力扣爆刷第114天之CodeTop100五连刷56-60

力扣爆刷第114天之CodeTop100五连刷56-60 文章目录 力扣爆刷第114天之CodeTop100五连刷56-60一、78. 子集二、105. 从前序与中序遍历序列构造二叉树三、43. 字符串相乘四、155. 最小栈五、151. 反转字符串中的单词 一、78. 子集 题目链接&#xff1a;https://leetcode.cn/prob…

一文了解RAID技术基本概念

RAID是数据存储技术&#xff0c;旨在提高磁盘的IO吞吐以及提供更为可靠的数据安全。在实际工作中经常听到RAID相关名称&#xff0c;那么RAID技术的基本概念是什么、不同RAID级别有什么特性&#xff0c;本文将简单介绍&#xff0c;以了解。 1、RAID技术基本概念 1.1 RAID基本概…

uniapp中uni.navigateTo传递变量

效果展示&#xff1a; 核心代码&#xff1a; uniapp中uni.navigateTo传递变量 methods: {changePages(item) {setDatas("maintenanceFunName", JSON.stringify(item)).then((res) > {uni.navigateTo({url: /pages/PMS/maintenance/maintenanceTypes/maintenanceT…

python开发poc2,爆破脚本

#本课知识点和目的&#xff1a; ---协议模块使用&#xff0c;Request 爬虫技术&#xff0c;简易多线程技术&#xff0c;编码技术&#xff0c;Bypass 后门技术 下载ftp服务器模拟器 https://lcba.lanzouy.com/iAMePxl378h 随便创建一个账户&#xff0c;然后登录进去把ip改成…

从头开发一个RISC-V的操作系统(四)嵌入式开发介绍

文章目录 前提嵌入式开发交叉编译GDB调试&#xff0c;QEMU&#xff0c;MAKEFILE练习 目标&#xff1a;通过这一个系列课程的学习&#xff0c;开发出一个简易的在RISC-V指令集架构上运行的操作系统。 前提 这个系列的大部分文章和知识来自于&#xff1a;[完结] 循序渐进&#x…
最新文章