【Java 数据结构】LinkedList与链表

LinkedList与链表

  • 1. ArrayList的缺陷
  • 2. 链表
    • 2.1 链表的概念及结构
    • 2.2 链表的实现
  • 3. LinkedList的模拟实现
  • 4.LinkedList的使用
    • 4.1 什么是LinkedList
    • 4.2LinkedList的使用
  • 5. ArrayList和LinkedList的区别

1. ArrayList的缺陷

上节课已经熟悉了ArrayList的使用,并且进行了简单模拟实现。通过源码知道,ArrayList底层使用数组来存储元素:

public class ArrayList<E> extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable{// ...// 默认容量是10private static final int DEFAULT_CAPACITY = 10;//...// 数组:用来存储元素transient Object[] elementData; // non-private to simplify nested class access// 有效元素个数private int size;public ArrayList(int initialCapacity) {if (initialCapacity > 0) {this.elementData = new Object[initialCapacity];} else if (initialCapacity == 0) {this.elementData = EMPTY_ELEMENTDATA;} else {throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);}}// ...
}

由于其底层是一段连续空间,当在ArrayList任意位置插入或者删除元素时,就需要将后序元素整体往前或者往后搬移,时间复杂度为O(n),效率比较低,因此ArrayList不适合做任意位置插入和删除比较多的场景。因此:java集合中又引入了LinkedList,即链表结构。

2. 链表

2.1 链表的概念及结构

链表是一种物理存储结构上非连续存储结构,数据元素的逻辑顺序是通过链表中的引用链接次序实现的 。
在这里插入图片描述
实际中链表的结构非常多样

  1. 单向或者双向

在这里插入图片描述

  • 带头或者不带头
    在这里插入图片描述
  • 循环或者非循环
    在这里插入图片描述
    虽然有这么多的链表的结构,但是我们重点掌握两种:
  • 无头单向非循环链表:结构简单,一般不会单独用来存数据。实际中更多是作为其他数据结构的子结构,如哈希桶、图的邻接表等等。另外这种结构在笔试面试中出现很多
  • 无头双向链表:在Java的集合框架库中LinkedList底层实现就是无头双向循环链表。

2.2 链表的实现

自己实现接口ILIST

public interface IList {//头插法void addFirst(int data);//尾插法void addLast(int data);//任意位置插入,第一个数据节点为0号下标void addIndex(int index,int data);//查找是否包含关键字key是否在单链表当中boolean contains(int key);//删除第一次出现关键字为key的节点void remove(int key);//删除所有值为key的节点void removeAllKey(int key);//得到单链表的长度int size();void clear();void display();
}

链表实现

public class MySingleList implements IList {//节点的内部类static class ListNode {public int val;public ListNode next;public ListNode(int val) {this.val = val;}}public ListNode head;//public int usedSize;//可以定义public void createList() {ListNode node1 = new ListNode(12);ListNode node2 = new ListNode(23);ListNode node3 = new ListNode(34);ListNode node4 = new ListNode(45);ListNode node5 = new ListNode(56);node1.next = node2;node2.next = node3;node3.next = node4;node4.next = node5;this.head = node1;}public void addFirst(int data) {ListNode node = new ListNode(data);if (this.head == null) {this.head = node;} else {node.next = this.head;this.head = node;}}public void addLast(int data) {ListNode node = new ListNode(data);ListNode cur = this.head;if (this.head == null) {this.head = node;} else {//找到尾巴while (cur.next != null) {cur = cur.next;}//cur 现在指向了最后一个节点cur.next = node;}}public void addIndex(int index, int data) {if (index < 0 || index > size()) {//抛自定义的异常return;}if (index == 0) {addFirst(data);return;}if (index == size()) {addLast(data);return;}ListNode cur = searchPrev(index);ListNode node = new ListNode(data);node.next = cur.next;cur.next = node;}private ListNode searchPrev(int index) {ListNode cur = this.head;int count = 0;while (count != index - 1) {cur = cur.next;count++;}return cur;}public boolean contains(int key) {ListNode cur = this.head;while (cur != null) {if (cur.val == key) {return true;}cur = cur.next;}return false;}public void remove(int key) {if (this.head == null) {//一个节点都没有 无法删除!return;}if (this.head.val == key) {this.head = this.head.next;return;}//1. 找到前驱ListNode cur = findPrev(key);//2、判断返回值是否为空?if (cur == null) {System.out.println("没有你要删除的数字");return;}//3、删除ListNode del = cur.next;cur.next = del.next;}/*** 找到关键字key的前一个节点的地址** @param key* @return*/private ListNode findPrev(int key) {ListNode cur = this.head;while (cur.next != null) {if (cur.next.val == key) {return cur;}cur = cur.next;}return null;}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;cur = cur.next;} else {prev = cur;cur = cur.next;}}if (head.val == key) {head = head.next;}}public int size() {int count = 0;ListNode cur = this.head;while (cur != null) {count++;cur = cur.next;}return count;}public void clear() {ListNode cur = head;while (cur != null) {ListNode curNext = cur.next;//cur.val = null;cur.next = null;cur = curNext;}head = null;}public void display() {ListNode cur = this.head;while (cur != null) {System.out.print(cur.val + " ");cur = cur.next;}System.out.println();}/*** 这个是从指定位置开始打印** @param newHead*/public void display(ListNode newHead) {ListNode cur = newHead;while (cur != null) {System.out.print(cur.val + " ");cur = cur.next;}System.out.println();}
}

3. LinkedList的模拟实现

// 2、无头双向链表实现
public class MyLinkedList {//头插法public void addFirst(int data){ }//尾插法public void addLast(int data){}//任意位置插入,第一个数据节点为0号下标public void addIndex(int index,int data){}//查找是否包含关键字key是否在单链表当中public boolean contains(int key){}//删除第一次出现关键字为key的节点public void remove(int key){}//删除所有值为key的节点public void removeAllKey(int key){}//得到单链表的长度public int size(){}public void display(){}public void clear(){}
}

4.LinkedList的使用

4.1 什么是LinkedList

LinkedList的底层是双向链表结构(链表后面介绍),由于链表没有将元素存储在连续的空间中,元素存储在单独的节点中,然后通过引用将节点连接起来了,因此在在任意位置插入或者删除元素时,不需要搬移元素,效率比较高。
在这里插入图片描述
在集合框架中,LinkedList也实现了List接口
在这里插入图片描述

【说明】

  1. LinkedList实现了List接口
  2. LinkedList的底层使用了双向链表
  3. LinkedList没有实现RandomAccess接口,因此LinkedList不支持随机访问
  4. LinkedList的任意位置插入和删除元素时效率比较高,时间复杂度为O(1)
  5. LinkedList比较适合任意位置插入的场景

4.2LinkedList的使用

  1. LinkedList的构造
    在这里插入图片描述
public static void main(String[] args) {// 构造一个空的LinkedListList<Integer> list1 = new LinkedList<>();List<String> list2 = new java.util.ArrayList<>();list2.add("JavaSE");list2.add("JavaWeb");list2.add("JavaEE");// 使用ArrayList构造LinkedListList<String> list3 = new LinkedList<>(list2);
}
  1. LinkedList的其他常用方法介绍
    在这里插入图片描述
  2. LinkedList的遍历
public static void main(String[] args) {LinkedList<Integer> list = new LinkedList<>();list.add(1); // add(elem): 表示尾插list.add(2);list.add(3);list.add(4);list.add(5);list.add(6);list.add(7);System.out.println(list.size());
// foreach遍历for (int e:list) {System.out.print(e + " ");}System.out.println();
// 使用迭代器遍历---正向遍历ListIterator<Integer> it = list.listIterator();while(it.hasNext()){System.out.print(it.next()+ " ");}System.out.println();
// 使用反向迭代器---反向遍历ListIterator<Integer> rit = list.listIterator(list.size());while (rit.hasPrevious()){System.out.print(rit.previous() +" ");}System.out.println();}

5. ArrayList和LinkedList的区别

在这里插入图片描述

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

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

相关文章

虚拟机扩容后黑屏卡死解决方法

亲测有效&#xff0c;首先一般是在扩容后黑屏的&#xff0c;现象为开机后看到个横线光标不闪&#xff0c;黑屏&#xff0c;进入不了桌面。原因是硬盘已经满了&#xff0c;所以解决方法就是清理硬盘。所以首先还是要解决登录问题。 开机时按 esc 键进入 GNU GRUB&#xff0c;选择…

windows平台使用tensorRT部署yolov5详细介绍,整个流程思路以及细节。

目录 Windows平台上使用tensorRT部署yolov5 前言&#xff1a; 环境&#xff1a; 1.为什么要部署&#xff1f; 2.那为什么部署可以解决这个问题&#xff1f;&#xff08;基于tensorRT&#xff09; 3.怎么部署&#xff08;只讨论tensorRT&#xff09; 3.0部署的流程 3.1怎…

GoLang和GoLand的安装和配置

1. GoLang 1.1 特点介绍 Go 语言保证了既能达到静态编译语言的安全和性能&#xff0c;又达到了动态语言开发维护的高效率&#xff0c;使用一个表达式来形容 Go 语言&#xff1a;Go C Python , 说明 Go 语言既有 C 静态语言程序的运行速度&#xff0c;又能达到 Python 动态语…

闭包的理解?闭包使用场景

说说你对闭包的理解&#xff1f;闭包使用场景 #一、是什么 一个函数和对其周围状态&#xff08;lexical environment&#xff0c;词法环境&#xff09;的引用捆绑在一起&#xff08;或者说函数被引用包围&#xff09;&#xff0c;这样的组合就是闭包&#xff08;closure&#…

Vite+Vue3使用Vue-i18n笔记

一、下载依赖 vue-i18n yarn add vue-i18n创建存放语言文件的目录 以及配置文件的配置 我是在src/lang 新建index.ts、cn.ts、en.ts以及test文件夹其中再分别新建cn.ts以及en.ts /lang/index.ts 用于导出vue-i18n需要的配置对象 import en from "./en.ts"; import…

无人机在三维空间中的转动问题

前提 这篇博客是对最近一个有关无人机拍摄图像项目中所学到的新知识的一个总结&#xff0c;比较杂乱&#xff0c;没有固定的写作顺序。 无人机坐标系旋转问题 上图是无人机坐标系&#xff0c;绕x轴是翻滚(Roll)&#xff0c;绕y轴是俯仰(Pitch)&#xff0c;绕z轴是偏航(Yaw)。…

开发工具git分支冲突解决

在团队协作的软件开发过程中&#xff0c;Git是一款广泛使用的版本控制系统。然而&#xff0c;当多个开发者同时修改同一文件或代码段时&#xff0c;就会产生分支冲突。解决这些冲突需要仔细的协调和技术知识。本篇博客将介绍Git分支冲突的解决方法&#xff0c;以及开发工具和最…

代码随想录 Leetcode108. 将有序数组转换为二叉搜索树

题目&#xff1a; 代码(首刷自解 2024年1月31日&#xff09;&#xff1a; class Solution { public:TreeNode* recursion(vector<int>& nums, int left, int right) {if (left > right) return nullptr;int mid left (right-left)/2;TreeNode* node new TreeN…

2024西湖论剑misc方向wp

每年的misc都是最无聊坐牢的 数据安全-easy_tables import pandas as pd import hashlib from datetime import datetimeusers_df pd.read_csv(users.csv) permissions_df pd.read_csv(permissions.csv) tables_df pd.read_csv(tables.csv) actionlog_df pd.read_csv(acti…

响应式Web开发项目教程(HTML5+CSS3+Bootstrap)第2版 例5-5 Canvas 绘制三角形

代码 <!doctype html> <html> <head> <meta charset"utf-8"> <title>Canvas 绘制三角形</title> </head><body><canvas id"cavsElem">您的浏览器不支持Canvas&#xff0c;请升级浏览器</canvas…

数据恢复之道:DevicData-P-XXXXXXXX勒索病毒的预防与恢复攻略

尊敬的读者&#xff1a; 随着科技的发展&#xff0c;网络安全问题愈发突出&#xff0c;而勒索病毒作为其中的一种恶意软件&#xff0c;正不断演进成为威胁用户数据安全的严重问题。本文将深入介绍.DevicData-P-XXXXXXXX勒索病毒的特征&#xff0c;提供被感染文件的恢复方法&am…

【算法与数据结构】300、LeetCode最长递增子序列

文章目录 一、题目二、解法三、完整代码 所有的LeetCode题解索引&#xff0c;可以看这篇文章——【算法和数据结构】LeetCode题解。 一、题目 二、解法 思路分析&#xff1a;   程序如下&#xff1a; class Solution { public:int lengthOfLIS(vector<int>& nums)…