Java——LinkedList

2024-06-14 09:12
文章标签 java linkedlist

本文主要是介绍Java——LinkedList,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、链表

1.1 链表的概念及结构

链表在逻辑层面上是连续的,在物理层面上不一定是连续的

链表结构可分为,单向或双向、带头或不带头、循环或非循环,组合共计8种

重点:无头单向非循环链表、无头双向链表

1.2 模拟实现无头单向非循环链表

一个链表由若干节点组成,结合 内部类 知识,可将节点类定义在链表类中,成为内部类

public class MySingleLinkedList {static class ListNode {//该内部类中定义的是节点的属性public int val;public ListNode next;public ListNode(int val) {this.val = val;}}public ListNode head;//链表的头节点,定义在MySingleLinkedList类中}

下面以穷举的方式创建链表方便理解(真正创建链表并非如此)

//MySingleLinkedList类//该方法创建一个链表,头节点为node1,当该方法结束后,变量node1...都会销毁,只剩下头节点为head的链表public void createdList(){ListNode node1 = new ListNode(1);ListNode node2 = new ListNode(2);ListNode node3 = new ListNode(3);ListNode node4 = new ListNode(4);ListNode node5 = new ListNode(5);node1.next = node2;node2.next = node3;node3.next = node4;node4.next = node5;this.head = node1;}

打印链表

//MySingleLinkedList 类public void display() {ListNode cur = head; //若直接使用head进行遍历打印,将只能打印一次,再次调用该函数,头节点就不在原来的位置了while(cur != null) { //注意!此处若写成 cur.next != null 则不会打印最后一个节点System.out.print(cur.val + " ");cur = cur.next;}}

求链表长度:

    //遍历即可public int size() {ListNode cur = head;int count = 0;while(cur != null) {cur = cur.next;count++;}return count;}

头插法:

    public void addFirst(int data) {ListNode newNode = new ListNode(data);newNode.next = head;head = newNode;}

尾插法:

    public void addLast(int data) {ListNode newNode = new ListNode(data);//不要忘记:判空!if(head == null) {head = newNode;return;}ListNode cur = head;while(cur.next != null) { //此处若写成 cur.next != null 则不会打印最后一个节点cur = cur.next;}cur.next = newNode;}

在index位置插入

// IndexNotLegalException 异常类
public class IndexNotLegalException extends RuntimeException{public IndexNotLegalException() {}public IndexNotLegalException(String msg) {super(msg);}
}// MySingleLinkedList 类public void addIndex(int index, int data) {//1、判断index合法性try{checkIndex(index);}catch(IndexNotLegalException e) {e.printStackTrace();}//2、index == 0 || index == size()if(index == 0) {addFirst(data);return;}if(index == size()) {addLast(data);return;}//3、找到index的前一个位置ListNode cur = findIndexSubOne(index);//4、进行连接ListNode node = new ListNode(data);node.next = cur.next;cur.next = node;}private void checkIndex(int index) throws IndexNotLegalException{if(index < 0 || index > size()) {throw new IndexNotLegalException("index不合法!");}}private ListNode findIndexSubOne(int index) {int count = 0;ListNode cur = head;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;}//若头节点为keywhile(head.val == key) {head = head.next;return;}ListNode cur = head;//遍历找到值为key的节点while(cur.next != null) {if(cur.next.val == key) {cur.next = cur.next.next;return;}cur = cur.next;}System.out.println("没有找到要删除的数字!");}

删除所有值为key的节点

    public void removeAllKey(int key) {//判空if (this.head == null) {return;}//快慢指针ListNode prev = head;ListNode cur = head.next;while(cur != null) {if(cur.val == key) {prev.next = cur.next;}else {prev = cur;}cur = cur.next;}//处理头节点,当上述操作完成后,只剩下头节点没有判断//该方法优于一上来就判断头节点if(head.val == key) {head =head.next;}}

清空链表

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

1.3 模拟实现无头双向非循环链表

public class MyLinkedList {static class ListNode {public int data;public ListNode prev;//前驱节点public ListNode next;//后继节点public ListNode(int data){this.data = data;}}public ListNode head;//头节点public ListNode last;//尾节点//得到单链表的长度public int size(){int count = 0;ListNode cur = head;while(cur != null) {count++;cur = cur.next;}return count;}public void display(){ListNode cur = head;while(cur != null) {System.out.print(cur.data + " ");cur = cur.next;}System.out.println();}//查找是否包含关键字key是否在单链表当中public boolean contains(int key){ListNode cur = head;while(cur != null) {if(cur.data == 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 {head.prev = node;node.next = head;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(IndexIllegalException e) {e.printStackTrace();}if(index == 0) {addFirst(data);return;}if(index == size()) {addLast(data);return;}ListNode node = new ListNode(data);ListNode cur = findIndex(index);node.next = cur;node.prev = cur.prev;cur.prev.next = node;cur.prev = node;}private ListNode findIndex(int index) {ListNode cur = head;while(index != 0) {cur = cur.next;index--;}return cur;}private void checkIndex(int index) throws IndexIllegalException{if(index < 0 || index > size()) {throw new IndexIllegalException("双向链表index不合法!");}}//删除第一次出现关键字为key的节点public void remove(int key){ListNode cur = head;while(cur != null) {if(cur.data == key) {if(cur == head) {head = head.next;if(head != null) {head.prev = null;}else {last = null;}}else if(cur == last) {cur.prev.next = null;last = cur.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.data == key) {if(cur == head) {head = head.next;if(head != null) {head.prev = null;}else {last = null;}}else if(cur == last) {cur.prev.next = null;last = cur.prev;}else {cur.prev.next = cur.next;cur.next.prev = cur.prev;}}cur = cur.next;}}public void clear(){ListNode cur = head.next;while(cur != null) {cur = head.next;head.prev = null;head.next = null;head = cur;}head = last = null;}
}

链表遍历方式:

    public static void main(String[] args) {LinkedList<Integer> list = new LinkedList<>();list.add(1);list.add(2);list.add(3);//直接sout打印System.out.println(list);System.out.println("======");//foreatch循环打印for(Integer x : list) {System.out.print(x + " ");}System.out.println();System.out.println("======");//for循环打印for (int i = 0; i < list.size(); i++) {System.out.print(list.get(i) + " ");}System.out.println();System.out.println("======");//Iterator打印Iterator<Integer> it = list.iterator();while(it.hasNext()) {System.out.print(it.next() + " ");}System.out.println();System.out.println("======");//ListIterator可以倒着打印ListIterator<Integer> it3 = list.listIterator(list.size());while(it3.hasPrevious()) {System.out.print(it3.previous() + " ");}}

运行结果:

2、ArrayList 和 LinkedList 的区别

不同点ArrayListLinkedList
存储空间上逻辑&物理均连续逻辑上连续,物理上不一定连续
随机访问支持,时间复杂度为O(1)不支持,时间复杂度为O(N)
头插需要搬运元素,O(N)只需修改引用的指向,O(1)
插入空间不够时需要扩容没有容量概念
应用场景元素高效存储+频繁访问频繁在任意位置插入删除操作

这篇关于Java——LinkedList的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1059978

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap