LinkedList与链表

[本节目标]

1.ArrayList的缺陷

2.链表

3.链表相关oj题

4.LinkedList的模拟实现

5.LinkedList的使用

6.ArratList和LinkedList的区别

1. ArrayList的缺陷

上篇博客已经熟悉了ArrayList的使用,并且进行了简单模拟实现,ArrayList底层使用数组来储存元素:

public class ArrayList<E> extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
 // ...
 // 默认容量是10
  private 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. 从图上可以看出来,链式结构在逻辑上是连续的,但是在物理结构上是不一定连续的.

2.现实中的结点一般都是从堆上申请出来的

3.从堆上申请的空间,是按照一定策略来分配的,两次申请的空间可能连续,也可能不连续

 实际中链表的结构非常多样,以下情况结合起来就有8种链表结构:

1.单向或者双向

2.带头或者不带头

3.循环或者非循环

虽然有很多的链表的结构,但是我们重点掌握两种:

1.无头单向非循环链表,结构简单,一般不会单独来存数据,实际中更多是作为其他数据结构的子结构.如哈希桶,图的邻接表,另外这种结构在笔试面试中出现很多.

2.无头双向链表:在java中的集合框架中LinkedList底层实现就是无头双向链表

2.2 链表的使用和体现

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

3. LinkedList的模拟实现

public class MyListNode {

    static class ListNode {
        int value;
        public ListNode next;
        public ListNode prev;

        public ListNode(int value) {
            this.value = value;
        }
    }

    public ListNode head;

    public void createlist() {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        this.head = node1;
    }

    public void addFirst(int data){
        Listnode node = new Listnode(data);
       if(head==null){
           head=node;
           last = node;
       }
       else{
           node.next=head;
           node.next = head;
           head.prev = node;
           head= node;
       }
    }

    public void addLast(int data){
        Listnode node = new Listnode(data);
        if(head==null){
            head=node;
            last=node;
        }
        else{
            last.next = node;
            node.prev=last;
            last =node;
        }
    }

    

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

   public void remove(int key){
        Listnode cur =head;
        while(cur != null){
            if(cur.val == key){
                head = head.next;
                if(head==null){
                    last=null;
                 }
                else{
                    head.prev.next= cur.next;
                    if(cur.next==null){
                        last=last.next;
                    }
                }
                return;
            }
            else{
                cur =cur.next;
            }
        }
    }
public void removeAllKey(int key) {
        Listnode cur = head;
        while (cur != null) {
            if (cur.val == key) {
                head = head.next;
                if (head == null) {
                    last = null;
                } else {
                    head.prev.next = cur.next;
                    if (cur.next == null) {
                        last = last.next;
                    }
                }
            }
            cur = cur.next;
        }
    }


   public void addIndex(int index,int data){
        Listnode node = new Listnode(data);
        int len = size();
        if(index<0 || index>size()){
            return;
        }
        if(index==0){
            addFirst(data);
        }
        if(index==size()){
            addLast(data);
        }
        Listnode cur = head;
        int count =0;
        while(count<index){
            cur=cur.next;
            count++;
        }
        cur.prev.next = node;
        node.prev=cur.prev;
        node.next=cur;
        cur.prev = node;
    }

    public boolean contains(int key) {
        ListNode cur = head;
        while (cur != null){
            if(cur.value == key){
                return true;
            }
            cur = cur.next;
        }
       return false;
    }
    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.next != null) {
                System.out.println(cur.value + " ");
                cur = cur.next;
            }
            System.out.println(cur.value);
        }
}




4. LinkedList的使用

4.1 什么是LinkedList

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

[说明]

1.LinkedList实现了List接口

2.LinkedList的底层使用了双向链表

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

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

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

4.2 LinkedList的使用

1.LinkedList的构造

 public static void main(String[] args) {
        List<Integer> list1 = new LinkedList<>();
        List<String> list2 = new ArrayList<>();
        list2.add("javase");
        list2.add("javaee");
        list2.add("数据结构");
        List<String> list3 = new LinkedList<>(list2);
    }

2.LinkedList的其他常用方法介绍

方法                                                               解释
boolean add(E e)                                           尾插 e
void add(int index, E element)                       将 e 插入到 index 位置
boolean addAll(Collection<? extends E> c)   尾插 c 中的元素
E remove(int index)                                        删除 index 位置元素
boolean remove(Object o)                              删除遇到的第一个 o
E get(int index)                                               获取下标 index 位置元素
E set(int index, E element)                             将下标 index 位置元素设置为 element
void clear()                                                     清空
boolean contains(Object o)                            判断 o 是否在线性表中
int indexOf(Object o)                                       返回第一个 o 所在下标
int lastIndexOf(Object o)                                  返回最后一个 o 的下标
List<E> subList(int fromIndex, int toIndex)      截取部分 list

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());
  System.out.println(list);
 
  // 在起始位置插入0
  list.add(0, 0);  // add(index, elem): 在index位置插入元素elem
  System.out.println(list);
 
  list.remove();     // remove(): 删除第一个元素,内部调用的是removeFirst()
  list.removeFirst();   // removeFirst(): 删除第一个元素
  list.removeLast();   // removeLast(): 删除最后元素
  list.remove(1);  // remove(index): 删除index位置的元素
  System.out.println(list);
 
  // contains(elem): 检测elem元素是否存在,如果存在返回true,否则返回false
  if(!list.contains(1)){
    list.add(0, 1);
 }
  list.add(1);
  System.out.println(list);
  System.out.println(list.indexOf(1));  // indexOf(elem): 从前往后找到第一个elem的位置
  System.out.println(list.lastIndexOf(1));  // lastIndexOf(elem): 从后往前找第一个1的位置
  int elem = list.get(0);   // get(index): 获取指定位置元素
  list.set(0, 100);      // set(index, elem): 将index位置的元素设置为elem
  System.out.println(list);
 
  // subList(from, to): 用list中[from, to)之间的元素构造一个新的LinkedList返回
  List<Integer> copy = list.subList(0, 3); 
  System.out.println(list);
  System.out.println(copy);
  list.clear();        // 将list中元素清空
  System.out.println(list.size());
}

3.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的区别

6. 例题(帮助大家巩固链表)

1. 删除链表中等于给定值 val 的所有节点。203. 移除链表元素 - 力扣(LeetCode) 

public ListNode removeElements(ListNode head, int val) {
      if(head==null){
          return null;
      }
      ListNode pre = head;
      ListNode cur = head.next;
      while(cur != null){
          if(cur.val==val){
              pre.next = cur.next;
              cur=cur.next;
          }else{
              pre = pre.next;
              cur = cur.next;
          }
      }
      if(head.val == val){
          head = head.next;
      }
      return head;
    }


2. 反转一个单链表。206. 反转链表 - 力扣(LeetCode)

 public ListNode reverseList(ListNode head) {
        if(head==null){
            return null;
        }
ListNode cur =head.next;
ListNode slow =head;
while(cur!=null){
    ListNode curNex=cur.next;
cur.next=slow;
if(slow==head){
    cur.next.next=null;
}
slow=cur;
cur=curNex;
}
return slow;
    }


3. 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点。876. 链表的中间结点 - 力扣(LeetCode)

 public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null){
    fast=fast.next.next;
    slow=slow.next;
}
return slow;
}


4. 输入一个链表,输出该链表中倒数第k个结点。 面试题 02.02. 返回倒数第 k 个节点 - 力扣(LeetCode)

    public int kthToLast(ListNode head, int k) {
ListNode cur=head;
int count =0;
while(cur!= null){
    count++;
    cur=cur.next;
}
cur=head;
int a = count-k;
while(a!=0){
    a--;
    cur=cur.next;
}
return cur.val;
    }


5. 将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。21. 合并两个有序链表 - 力扣(LeetCode)

 public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode node = new ListNode(-1);
ListNode tem =  node;

while(list1 != null && list2 != null){
    if(list1.val<list2.val){
       
      tem.next = list1;
      //  tem = list1;//错误
        list1=list1.next;
    }
    else
    {
        tem.next = list2;
      //  tem = list2;//错误
         list2=list2.next;
    }
   tem = tem.next;
    }
     if(list1 != null){
tem.next = list1;
    }
    if(list2 != null){
tem.next = list2;
    }
    return node.next;
}


6. 编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前 。面试题 02.04. 分割链表 - 力扣(LeetCode)

public ListNode partition(ListNode head, int x) {
if(head == null){
    return null;
}
ListNode cur = head;
ListNode bs =null;
ListNode be = null;
ListNode as = null;
ListNode ae = null;
while(cur != null){
    if(cur.val < x){
    if(bs == null){
      be = cur;
      bs =cur;
    }else{
be.next = cur;
be = be.next;
    }
    }else{
if(as == null){
    as = cur;
    ae = cur;
}else{
ae.next = cur;
ae = ae.next;
}
    }
    cur= cur.next;
    }
if(bs==null){
    return as;
}
if(as !=null){
    ae.next = null;
}
    be.next = as;
    return bs;
}


7. 链表的回文结构。LCR 027. 回文链表 - 力扣(LeetCode)

 public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
    fast = fast.next.next;
    slow = slow.next;
}
ListNode cur = slow.next;
while(cur != null){
ListNode curnex = cur.next;
cur.next = slow;
slow = cur;
cur = curnex;
}
while(head != slow){
    if(head.val != slow.val){
      return false;  
    }
    if(head.next == slow){
        return true;
    }
    head = head.next;
    slow = slow.next;
}
return true;
    }


8. 输入两个链表,找出它们的第一个公共结点。160. 相交链表 - 力扣(LeetCode)

 public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
   ListNode p1 = headA;
   ListNode p2 = headB;
   int count1 = 0;
   int count2 = 0;
while(p1!=null){
    p1=p1.next;
count1++;
}
while(p2!=null){
    p2=p2.next;
    count2++;
}
p1= headA;
p2 =headB;
int len =count1-count2;
if(len<0){
p1 =headB;
p2 =headA;
len = count2-count1;
}
while(len!=0){
    len--;
    p1=p1.next;
}
while(p1!=p2){
    p1=p1.next;
    p2=p2.next;
}
if(p1==null){
    return null;
}
return p1;

    }

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

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

相关文章

K8S 中对 Windows 节点的利用

目录 漏洞概述 漏洞详情 ​编辑 漏洞验证 补丁分析 在集群中探索 参考资料 在许多组织中&#xff0c;所运行的很大一部分服务和应用是 Windows 应用。Windows 容器提供了一种封装进程和包依赖项的方式&#xff0c;从而简化了 DevOps 实践&#xff0c;令 Windows 应用程序…

深入探究MongoDB:从基础到实战,一个全面的指南

MongoDB:海量数据库的介绍 定义与命名由来: MongoDB源自词“humongous”,意味着“巨大无比”。因此,MongoDB可译为“海量数据库”。类型: MongoDB是一种非关系型(NoSQL)数据库。与传统的关系型数据库相比,它的显著特点是不使用SQL语句。数据结构更灵活,没有固定的数据类…

装饰模式(单一责任)

Decorator&#xff08;装饰模式&#xff1a;单一责任模式&#xff09; 链接&#xff1a;装饰模式实例代码 解析 目的 在某些情况下我们可能会“过度地使用继承来扩展对象的功能”&#xff0c;由于继承为类型引入的静态特质&#xff0c;使得这种扩展方式缺乏灵活性&#xff…

【C语言】指针详解(四)

目录 1.assert断言 2.指针的使用和传址调用 2.1strlen的模拟使用 2.2传值调用和传址调用 1.assert断言 assert.h头文件定义了宏 assert()&#xff0c;用于在运行时确保程序符合指定条件&#xff0c;如果不符合&#xff0c;就报错终止运行。这个宏常常被称为“断言”。 例如…

【Azure 架构师学习笔记】- Power Platform(1) - 简介

本文属于【Azure 架构师学习笔记】系列。 本文属于【Power Platform】系列。 Power Platform 它是一个SaaS平台&#xff0c;支持和延伸M365&#xff0c; Dynamics 365和Azure甚至其他第三方服务。主要提供低代码&#xff0c;自动化&#xff0c;数据驱动和定制化业务逻辑的服务…

NFC物联网一次性口令认证解决方案

物联网是由无线传感器网络、射频识别(RadioFrequency Identificalion&#xff0c;RFID)网络、互联网等构成的一种复合型网络&#xff0c;具有部分终端设备体积小、存储和计算处理能力弱的特点。顾名思义&#xff0c;物联网就是“物物相连的互联网”&#xff0c;也就是说,物联网…

Spark与Hadoop的关系和区别

在大数据领域&#xff0c;Spark和Hadoop是两个备受欢迎的分布式数据处理框架&#xff0c;它们在处理大规模数据时都具有重要作用。本文将深入探讨Spark与Hadoop之间的关系和区别&#xff0c;以帮助大家的功能和用途。 Spark和Hadoop简介 1 Hadoop Hadoop是一个由Apache基金会…

工具系列:TimeGPT_(1)获取token方式和初步使用

文章目录 介绍获取Token用法数据的重要要求使用DateTime索引推断频率。 介绍 Nixtla的TimeGPT是一种用于时间序列数据的生成式预训练预测模型。TimeGPT可以在没有训练的情况下&#xff0c;仅使用历史值作为输入&#xff0c;为新的时间序列生成准确的预测。TimeGPT可以用于各种…

亚马逊云科技 re:Invent 大会 - ElastiCache Serverless 模式来袭

大会介绍 亚马逊云科技的 re:Invent 大会是一年一度的&#xff0c;面向全球技术开发者科技盛会。几乎每次都会发布云科技、云计算等相关领域的产品重磅更新&#xff0c;不但将时下主流热门的技术不断整合&#xff0c;也未将来的发展标明了方向。 亚马逊云科技开发者社区为开发…

安卓系统和鸿蒙系统,哪个更适合老人使用

安卓系统和鸿蒙系统各有优势&#xff0c;但总体来说&#xff0c;鸿蒙系统可能更适合老人使用。以下是几个原因&#xff1a; 1.易用性&#xff1a; 鸿蒙系统针对老年人的使用习惯和需求进行了优化设计。它采用了更加直观、简洁的界面设计&#xff0c;降低复杂度并提升操作效率。…

Vue在页面上添加水印

第一步&#xff1a;在自己的项目里创建一个js文件&#xff1b;如图所示我在在watermark文件中创建了一个名为waterMark.js文件。 waterMark.js /** 水印添加方法 */ let setWatermark (str1, str2) > {let id 1.23452384164.123412415if (document.getElementById(id) …

为什么深度学习神经网络可以学习任何东西

下图你所看到的&#xff0c;是著名的曼德尔布罗特集&#xff0c;我们可以见证这个集合呈现出的复杂形态&#xff1a; 要理解神经网络如何学习曼德尔布罗特集&#xff0c;我们首先需要从最基础的数学概念讲起&#xff1a;什么是函数&#xff1f;函数本质上是一个将输入转化为输出…

AR智慧校园三维主电子沙盘系统研究及应用

一 、概述 易图讯科技(www.3dgis.top)自主研发的智慧校园三维主电子沙盘系统&#xff0c;采用B/S架构模式&#xff0c;采用自主可控高性能WebGIS可视化引擎&#xff0c;支持多用户客户端通过网络请求访问服务器地图和专题数据&#xff0c;提供地理信息数据、专题数据的并发访问…

问题解决 | Ubuntu重启无法进入系统

Ubuntu18.04重启无法进入系统&#xff0c;重开后如图 一直在加载系统内核4.15.0-213-generic,无法加载 错误原因 原本的系统是Ubuntu16.04,使用命令升级到Ubuntu18.04版本&#xff0c;升级重启后&#xff0c;远程无法连接&#xff01; 错误解决 第一步&#xff1a;进入GRUB…

java爬虫(jsoup)如何设置HTTP代理ip爬数据

目录 前言 什么是HTTP代理IP 使用Jsoup设置HTTP代理IP的步骤 1. 导入Jsoup依赖 2. 创建HttpProxy类 3. 设置代理服务器 4. 使用Jsoup进行爬取 结论 前言 在Java中使用Jsoup进行网络爬虫操作时&#xff0c;有时需要使用HTTP代理IP来爬取数据。本文将介绍如何使用Jsoup设…

2023年9月25日,开启华为鸿蒙应用开发新纪元!!!

鸿蒙&#xff01;鸿蒙&#xff01;鸿蒙&#xff01; 要说2023年IT圈最火爆的名词&#xff0c;一定是鸿蒙&#xff01; 2023年9月25日&#xff0c;华为发布会正式宣布2024年第一季度将推出HarmonyOS NEXT版本&#xff0c;这意味着鸿蒙原生应用开发将彻底摆脱Android手机系统&a…

实现阿里云oos云存储,简单几步

一、前言 虽然平常学习用的不多&#xff0c;但是用的时候再去找官方文档&#xff0c;也很繁琐&#xff0c;不如直接整理以下&#xff0c;方便粘贴复制&#xff0c;本文介绍两种图片上传方式①普通上传②服务端签名直传 1.普通上传 加载maven依赖 <dependency><grou…

【PHP】发送HTTP请求时参数快速组装

1.POST、GET参数组装 利用compact、http_build_query函数 // post的数组体$a 1;$b 2;$c $a $b;$array compact(a,b,c); // 组合请求参数print_r($array);// get的url组装$paramsStr http_build_query($array);print_r($paramsStr); 打印结果 2.一个请求示例 使用guzzle …

设计模式-依赖注入模式

设计模式专栏 模式介绍模式特点应用场景依赖注入和控制反转的区别代码示例Java实现依赖注入模式Python实现依赖注入模式 依赖注入模式在spring中的应用 模式介绍 依赖注入&#xff08;Dependency Injection&#xff0c;简称DI&#xff09;是一种面向对象编程中的设计模式&…

【宇宙猜想】AR文创入驻今日美术馆、北京天文馆等众多展馆,在AR互动中感受科技魅力!

近日&#xff0c;由「宇宙猜想」推出的AR系列文创产品先后入驻今日美术馆、北京天文馆、国家自然博物馆、上海天文馆、国家海洋馆、中华手工展馆等各大馆场并与其展开相关合作。 「宇宙猜想」致力于创造虚拟空间价值&#xff0c;用AR技术与文创产品碰撞出新的火花&#xff0c;为…
最新文章