Java: LinkedList的模拟实现

 一、双向链表简介

上一篇文章我介绍了单向链表的实现,单向链表的特点是:可以根据上一个节点访问下一个节点!但是,它有个缺点,无法通过下一个节点访问上一个节点!这也是它称为单向链表的原因。

  那么,可不可以实现这样一种链表,它既可以通过一个节点,访问其上一个节点和下一个节点,也是可以的!它就是我接下来要介绍的双向链表

  如图:与单向链表不同的是,双向链表的每个节点包含三个域:val、pre、next,分别代表当前节点的值、上一个节点的地址、下一个节点的地址。



 

二、双向链表的实现

双向链表实现的全部代码:

 类文件:

 异常类代码:(IndexNotLegalException)

//自定义异常类:
public class IndexNotLegalException extends RuntimeException{public IndexNotLegalException() {}public IndexNotLegalException(String message) {super(message);}
}

双向链表实现代码:(MyLinkedList)

import javax.management.ListenerNotFoundException;
import java.util.List;public class MyLinkedList {//创建ListNode内部类class ListNode {public int val;public ListNode pre;//前驱public ListNode next;//后继public ListNode(int val) {this.val = val;}}public ListNode head;//标志头节点public ListNode last;//标志尾节点//返回链表长度的方法:public int size() {int count = 0;ListNode cur = head;while (cur != null) {cur = cur.next;count++;}return count;}//打印链表的方法;public void display() {ListNode cur = head;while (cur != null) {System.out.print(cur.val + " ");cur = cur.next;}System.out.println();}//查看是否波包含key关键字的方法: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);//如果head为nullif (head == null) {head = last = node;} else {head.pre = node;node.next = head;head = node;}}//尾部插入的方法:public void addLast(int data) {ListNode node = new ListNode(data);//如果head==nullif (head == null) {head = last = node;} else {last.next = node;node.pre = last;last = node;}}//指定位置插入的方法:public void addIndex(int index, int data) {//1、判断index是否合法try {checkIndex(index);} catch (IndexNotLegalException e) {e.printStackTrace();}//index==0,相当于头部插入if (index == 0) {addFirst(data);return;}//index==size(),相当于尾部插入if (index == size()) {addLast(data);return;}//0<index<size()if (index > 0 && index < size()) {//找到下标为index的节点ListNode cur = findIndex(index);//连接节点ListNode node = new ListNode(data);node.next = cur;node.pre = cur.pre;cur.pre.next = node;cur.pre = node;return;}}//找到index节点的方法:public ListNode findIndex(int index) {int count = index;ListNode cur = head;while (count != 0) {cur = cur.next;count--;}return cur;}//检查index是否合法的方法private void checkIndex(int index) {if (index < 0 || index > size()) {throw new IndexNotLegalException("Index 不合法!" + index);}}//删除第一次出现关键字key的节点public void remove(int key) {//使用cur寻找关键字所在的节点ListNode cur = head;while (cur != null) {if (cur.val == key) {if (cur == head) {//关键字在头节点head = head.next;//判断链表是否只有一个节点!if(head!=null){head.pre = null;}else{last=null;}} else { //关键字在尾节点if (cur == last) {cur.pre.next = cur.next;last = last.pre;} else {  //关键字在中间节点cur.pre.next = cur.next;cur.next.pre = cur.pre;}}return;}cur = cur.next;}}//删除所有值为key的节点public void removeAllKey(int key){//使用cur寻找关键字所在的节点ListNode cur = head;while (cur != null) {if (cur.val == key) {if (cur == head) {//关键字在头节点head = head.next;//判断链表是否只有一个节点!if(head!=null){head.pre = null;}else{last=null;}} else { //关键字在尾节点if (cur == last) {cur.pre.next = cur.next;last = last.pre;} else {  //关键字在中间节点cur.pre.next = cur.next;cur.next.pre = cur.pre;}}//return;注释该语句,使其多次删除关键字为key的节点}cur = cur.next;}}//删除列表public void clear(){ListNode cur=head;while(cur!=null){ListNode curN=cur.next;cur.pre=null;cur.next=null;cur=curN;}head=last=null;}
}

 



详细讲解: 

 首先创建一个class文件:MyLinkedList类和一个Test类,前者用来实现双向链表,后者用来使用链表!

  在这个MyLinkedList类中,我们需要定义一个内部类:ListNode类,表示节点类!这个节点类应该包含val、pre、next三个成员变量和val的构造方法!

创建好内部类后,就可以定义MyLinkedList类中的成员变量!它应该包括头节点head和尾节点last!



1、一些简单的方法: 

通过前面单向链表的学习,一些简单的方法就不再过多详细介绍,大家看着代码就能懂其中的意思。

  //返回链表长度的方法:public int size(){int count =0;ListNode cur=head;while(cur!=null){cur=cur.next;count++;}return count;}//打印链表的方法;public void display(){ListNode cur=head;while(cur!=null){System.out.print(cur.val+" ");cur=cur.next;}System.out.println();}//查看是否包含key关键字的方法:public boolean contains(int key){ListNode cur=head;while(cur!=null){if(cur.val==key){return true;}cur=cur.next;}return false;}


2、头部插入的方法: 

头部插入前,首先需要实例化应该ListNode类的节点! 

头部插入的时候,需要分为两种情况:head==null 或 head!=null

i>当head==null时:

此时链表没有节点,此时head和last应该指向同一个节点node

ii>当head!=null时:

第一步:将head.next的null修改为新节点的地址0x78

第二步:将node.next修改为head的地址0x12

第三步:  修改头节点,head=node

修改前:

修改后: 

代码实现:

//头部插入的方法public void addFirst(int data){ListNode node=new ListNode(data);//如果head为nullif(head==null){head=last=node;}else{head.pre=node;node.next=head;head=node;}}



3、尾部插入的方法:

尾部插入的方法与头部插入的方法逻辑上是一样的,也分为两种情况:head==null 或 head!=null

//尾部插入的方法:public void addLast(int data){ListNode node=new ListNode(data);//如果head==nullif(head==null){head=last=node;}else{last.next=node;node.pre=last;last=node;}}


4、指定位置插入的方法:

指定位置插入方法全部代码:

   //指定位置插入的方法:public void addIndex(int index, int data) {//1、判断index是否合法try {checkIndex(index);//调用了checkIndex方法,方法实现在下面} catch (IndexNotLegalException e) {e.printStackTrace();}//index==0,相当于头部插入if (index == 0) {addFirst(data);return;}//index==size(),相当于尾部插入if(index==size()){addLast(data);return;}//0<index<size()if(index>0&&index<size()){//找到下标为index的节点ListNode cur=findIndex(index);//调用了findIndex方法,方法实现在下面//连接节点ListNode node=new ListNode(data);node.next=cur;node.pre=cur.pre;cur.pre.next=node;cur.pre=node;return;}}//调用方法的实现://找到index节点的方法:public ListNode findIndex(int index){int count=index;ListNode cur=head;while(count!=0){cur=cur.next;count--;}return  cur;}//检查index是否合法的方法private void checkIndex(int index){if(index<0||index>size()){throw new IndexNotLegalException("Index 不合法!"+index);}}

详细介绍; 

指定插入的方法需要传入一个下标,在指定下标的节点之前插入一个节点!

那么,根据下标的值可以分为四种情况:
i>下标不合法

此时先自定义一个异常类:

另外,需要在MyLinkedList类中创建一个方法,用来判断下标是否合法,如果不合法,抛出该异常类

//检查index是否合法的方法private void checkIndex(int index){if(index<0||index>size()){throw new IndexNotLegalException("Index 不合法!"+index);}}

 此时,就可以在指定位置插入的方法中写下标不合法的代码:

ii>index==0

当index==0,相当于头插,此时调用头部插入的方法即可

iii>index==size()

当index==size(),相当于尾部插入,此时调用尾部插入的方法即可

iiii>index>0&&index<size() 

这种情况属于指定位置插入的正常情况,它既不是头部插入,也不是尾部插入,而是在两个节点中间插入!

首先,需要使用创建cur找到下标为index的节点,以图为例子:我们要在下标为2的节点前插入node新节点!

那么,实例化node之后,我们就得根据如图中的箭头将新节点连接到链表中。可以看到,要修改四个引用的内容!

node.pre=cur.pre;

node.next=cur;

cur.pre.next=node;

cur.pre=node;

修改后:

代码实现:

//0<index<size()if(index>0&&index<size()){//找到下标为index的节点ListNode cur=findIndex(index);//调用findIndex方法//连接节点ListNode node=new ListNode(data);node.next=cur;node.pre=cur.pre;cur.pre.next=node;cur.pre=node;return;}

 调用的findIndex方法:

也是写在MyLinkedList类内部:

 //找到index节点的方法:public ListNode findIndex(int index){int count=index;ListNode cur=head;while(count!=0){cur=cur.next;count--;}return  cur;}


5、删除第一次出现关键字key的节点的方法:

删除第一次出现关键字key的节点,首先,先实例化一个cur帮助我们找到想要删除的节点

然后再执行删除操作,cur所在节点的位置不同,所要执行的操作也不同,这里分为三种情况:

1、cur所在节点为中间节点

2、cur==head

3、cur==last

先来说说第一种情况:cur所在节点为中间节点

首先,我们使用cur找到了关键字为12所在的节点!然后,执行删除操作!

这里只需要将cur所在的前后节点依照如图箭头方向连接即可!

cur.pre.next=cur.next;

cur.next.pre=cur.pre;

第二种情况:cur==head

这种情况下,我们会发现,如果照搬第一种情况的代码

cur.pre.next=cur.next;//由于head.pre==null,因此会报错

cur.next.pre=cur.pre;

所以,此时,我们只需要将这么写

head=head.next;  //头节点换到下一个节点

head.pre=null;     //将新的头节点的pre修改为null

特殊情况:

如果链表中只有一个节点!

那么执行完语句head=head.next后,head==null,因此语句head.pre=null(相当于null.pre=null)会报错!

所以,在cur==head的情况下,我们还要解决链表只有一个节点的特殊情况:

if (cur == head) {//关键字在头节点head = head.next;//判断链表是否只有一个节点!if(head!=null){head.pre = null;}else{//只有一个节点的情况:last=null;}}

第三种情况:cur==last

此时,这种情况下,代码这么写:

cur.pre.next=cur.next;  //将前一个节点的next置为null(cur.next==null)

last=last.pre;                //last向前移动一个节点

代码实现:

//删除第一次出现关键字key的节点public void remove(int key) {//使用cur寻找关键字所在的节点ListNode cur = head;while (cur != null) {if (cur.val == key) {if (cur == head) {//关键字在头节点head = head.next;//判断链表是否只有一个节点!if(head!=null){head.pre = null;}else{last=null;}} else { //关键字在尾节点if (cur == last) {cur.pre.next = cur.next;last = last.pre;} else {  //关键字在中间节点cur.pre.next = cur.next;cur.next.pre = cur.pre;}}return;//删完一个就走}cur = cur.next;}}


6、删除所有值为key的节点的方法:

有了上一个方法的学习,这个方法那就很简单了,只需要注释掉return语句即可,我们可以回头看看上述代码,它的整体逻辑是删除第一个关键字为key的节点就结束循环,那么,我们是不是就可以在删除完一个节点后选择不结束该方法,让它继续删除呢。当然可以!

//删除所有值为key的节点public void removeAllKey(int key){//使用cur寻找关键字所在的节点ListNode cur = head;while (cur != null) {if (cur.val == key) {if (cur == head) {//关键字在头节点head = head.next;//判断链表是否只有一个节点!if(head!=null){head.pre = null;}else{last=null;}} else { //关键字在尾节点if (cur == last) {cur.pre.next = cur.next;last = last.pre;} else {  //关键字在中间节点cur.pre.next = cur.next;cur.next.pre = cur.pre;}}//return;注释该语句,使其多次删除关键字为key的节点}cur = cur.next;}}


7、清空链表方法:

这里清空链表的主要逻辑是将每一个节点的pre和next置为null,最后将head和last置为null 

//删除列表public void clear(){ListNode cur=head;while(cur!=null){ListNode curN=cur.next;cur.pre=null;cur.next=null;cur=curN;}head=last=null;}

 



三、LinkedList的使用

  上面我们讲解了如何实现双向链表,这其实是Java自带的LinkedList的底层实现,接下来让我们来学习Java自带的LinkedList吧!

1、LinkedList的构造

LinkedList有两个构造方法,在使用LinkedList之前,我们需要调用构造方法实例化一个对象。

方法:                                                解释:
LinkedList()                                       无参构造
public LinkedList(Collection<? extends E> c)         使用其他集合容器中元素构造List

第一个无参构造就不多解释了,因为比较好懂,那么我们来解释一下第二个构造方法可以传入那些参数?

首先,我们需要知道的是:

1、Collection是传入参数的类型

2、?表示:Collection<>中传入的类型

3、<? extends E>表示:?代表的这个类型要么继承E这个类型,要么继承E这个类型的子类

可以看到,第二个构造方法可以传入参数list,此时可能有以下疑问:

1、传入的参数类型是Collection类型的,那么为什么可以传入LinkedList类型的list呢?

答:LinkedList类型实现了Collection接口!

2、如何解释list符合<? extends E>

答:在实例化list的时候,LinkedList传入的参数类型是Integer,此时这个Integer代表  ?

      在实例化list2的时候,LinkedList传入的参数类型是Integer,此时这个Integr代表   E

      也即是说:? 继承了  E  这个类型,所以这个传入参数list是符合<? extends E>的

 

另外在实例化LinkedList的时候,因为LinkedList实现了List接口,因此在实例化的时候有两种写法:



 

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

全国计算机等级考试三级Linux应用与开发技术考试-习题汇总

https://blog.csdn.net/qq_42025798/article/details/119155696 3.第1章-计算机体系结构与操作系统-练习题-简答题 https://blog.csdn.net/qq_42025798/article/details/119186151 4.第1章-计算机体系结构与操作系统-练习题-填空题 https://blog.csdn.net/qq_42025798/article/…

android 资源文件混淆

AGP7.0以上引用AndResGuard有坑 记录下 在项目的build.gradle中添加如下 buildscript {ext.kotlin_version "1.4.31"repositories {google()jcenter()maven {url "https://s01.oss.sonatype.org/content/repositories/snapshots/"}}dependencies {class…

关东升老师力作!四本编程宝典,带你畅游编程世界

&#x1f31f;《看漫画学C》&#xff1a;关东升老师以漫画的形式&#xff0c;让你在欢笑中轻松掌握C编程的核心知识。不再枯燥&#xff0c;不再难懂&#xff0c;让编程变得有趣又简单&#xff01; &#x1f3a8;《MATLAB科研绘图与学术图表绘制从入门到精通》&#xff1a;关东升…

前端学习之DOM编程案例:全选反选案例

代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>全选反选</title> </head> <body><input type"checkbox" id"all">全选<ul><li><…

停用net stop mysql 服务名无效。

net stop mysql服务名 错误截图 解决方案 1. 按下 Win R 键&#xff0c;然后输入 services.msc 并按下 Enter 键&#xff0c;打开服务管理器 &#xff0c;查找与 MySQL 相关的服务 重新运行 net stop mysql服务名

CTF之社工-初步收集

题目就一个刷钻网站&#xff08;假的&#xff09; 扫描一下目录 发现还有一个登录界面 时间多的可以爆破一下&#xff08;反正我爆不出来&#xff09;&#xff0c;接着我们下载那个压缩包看看 发现是一个钓鱼小软件 没发现什么有用的信息那我们就去wireshark看看数据包喽&#…

Vue - 你可以说一说Veu3采用的Proxy与Vue2采用的defineProperty相比有什么优势吗

难度级别:中高级及以上 提问概率:85% 在Vue3中,双向绑定的核心API采用了ES6的Proxy代理方案,替换了Vue2的Object.defineProperty方案,那么这是为什么呢? 先说Object.defineProperty,我们知道它主要通过内部的set和get方法,劫持需要处理…

2.AK/SK鉴权

目录 什么是AK/SK AK/SK使用机制 时序图 什么是AK/SK 在云服务中&#xff0c;AK&#xff08;Access Key ID&#xff09;和SK&#xff08;Secret Access Key&#xff09;是访问云服务API的关键凭证对&#xff0c;主要用于身份验证和授权。AK是用户访问云服务的身份标识&…

1.数据结构和算法

文章目录 数据结构逻辑结构集合结构线性结构树形结构图形结构 物理结构顺序存储结构链式存储结构 算法基本特性目标 总结数据结构总结算法总结 数据结构 「数据结构」指的是&#xff1a;数据的组织结构&#xff0c;用来组织、存储数据。 逻辑结构 逻辑结构&#xff08;Logic…

Win安装SSH教程

在Windows操作系统上安装和配置SSH&#xff08;Secure Shell&#xff09;可以让你通过加密的方式远程连接和管理其他计算机或服务器。以下是安装和配置SSH的简单教程&#xff1a; 下载OpenSSH for Windows&#xff1a; 访问OpenSSH for Windows的官方网站&#xff08;https://g…

Linux(CentOS7)部署 y-api 接口管理平台

目录 前言 前置环境 mongodb node 安装 y-api 部署页面 启动 y-api 基本使用教程 前言 前后端分离时代&#xff0c;前后端通过接口文档来协作开发项目。一般开发过程中&#xff0c;由后端先编写接口文档&#xff0c;然后交付给前端&#xff0c;这时候前后端都根据这个…

HarmonyOS实战开发-如何实现蓝牙设备发现、配对、取消配对功能。

介绍 蓝牙技术是一种无线数据和语音通信开放的全球规范&#xff0c;它是基于低成本的近距离无线连接&#xff0c;为固定和移动设备建立通信环境的一种特殊的近距离无线技术连接。本示例通过ohos.bluetooth 接口实现蓝牙设备发现、配对、取消配对功能。实现效果如下&#xff1a…