手寫ArrayList和LinkedList

項目倉庫:https://gitee.com/bossDuy/hand-tear-collection-series
基于b站up生生大佬:https://www.bilibili.com/video/BV1Kp5tzGEc5/?spm_id_from=333.788.videopod.sections&vd_source=4cda4baec795c32b16ddd661bb9ce865

LinkedList

package com.yb0os1.List;import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;public class MyLinkedList<E> implements List<E> {private int size;private Node<E> tail;//尾節點private Node<E> head;//頭節點@Override//尾插法public void add(E element) {Node<E> node = new Node<>(tail, element, null);//尾插法if (tail != null) tail.next = node;else head = node;tail = node;++size;}@Override//對應的下標插入元素public void add(E element, int index) {//先判斷index是否合法if (index < 0 || index > size) {throw new IndexOutOfBoundsException("index:" + index + "size:" + size);}//尾插if (size == index) {add(element);return;}//中間插入 先找到在那個位置插入Node<E> indexNode = findNode(index);Node<E> newNode = new Node<>(indexNode.prev, element, indexNode);if (indexNode.prev == null) {//代表indexNode是頭節點head = newNode;} else {indexNode.prev.next = newNode;}indexNode.prev = newNode;++size;}private Node<E> findNode(int index) {Node<E> cur = head;while (index-- > 0) {cur = cur.next;}return cur;}@Overridepublic E remove(int index) {//先判斷index是否合法if (index < 0 || index >= size) {throw new IndexOutOfBoundsException("index:" + index + "size:" + size);}//找到要刪除的節點Node<E> indexNode = findNode(index);if (indexNode.prev == null) {//頭節點head = indexNode.next;} else{//非頭節點indexNode.prev.next = indexNode.next;}if (indexNode.next == null) {//尾節點tail = indexNode.prev;} else {//非尾節點indexNode.next.prev = indexNode.prev;}indexNode.next = null;indexNode.prev = null;--size;return indexNode.value;}@Overridepublic boolean remove(E element) {Node<E> curNode = head;int index = 0;while (curNode != null) {if (Objects.equals(element, curNode.value)) {remove(index);return true;}++index;curNode = curNode.next;}return false;}@Overridepublic E set(E element, int index) {//先判斷index是否合法if (index < 0 || index >= size) {throw new IndexOutOfBoundsException("index:" + index + "size:" + size);}Node<E> indexNode = findNode(index);E oldValue = indexNode.value;indexNode.value = element;return oldValue;}@Overridepublic E get(int index) {//先判斷index是否合法if (index < 0 || index >= size) {throw new IndexOutOfBoundsException("index:" + index + "size:" + size);}Node<E> indexNode = findNode(index);return indexNode.value;}@Overridepublic int size() {return size;}/*** Returns an iterator over elements of type {@code T}.** @return an Iterator.*/@Overridepublic Iterator<E> iterator() {return new LinkedListIterator();}private class LinkedListIterator implements Iterator<E> {Node<E> curNode = head;@Overridepublic boolean hasNext() {return curNode!=null;}/*** Returns the next element in the iteration.** @return the next element in the iteration* @throws NoSuchElementException if the iteration has no more elements*/@Overridepublic E next() {if (curNode==null){throw new NoSuchElementException();}E value = curNode.value;curNode = curNode.next;return value;}}private class Node<E> {E value;Node<E> next;//后繼Node<E> prev;//前驅public Node(E value) {this.value = value;}public Node(Node<E> prev, E value, Node<E> next) {this.value = value;this.next = next;this.prev = prev;}}
}

ArrayList

package com.yb0os1.List;import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;public class MyArrayList<E> implements List<E> {private Object[] table;//默認private final static int DEFAULT_CAPACITY = 10;//默認容量private int size;//實際的大小public MyArrayList() {this.table = new Object[DEFAULT_CAPACITY];}public MyArrayList(int initialCapacity) {if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: " +initialCapacity);this.table = new Object[initialCapacity];}//插入一個元素,在size的位置插入元素 也就是尾端插入元素@Overridepublic void add(E element) {//先判斷size是否等于容量,等于的話需要先擴容,不等于才可以插入if (size >= table.length) {resize();}table[size++] = element;}//在對應的index插入元素@Overridepublic void add(E element, int index) {//先判斷index是否合法if (index < 0 || index > size) {throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);}//判斷是否需要擴容后if (table.length == size) {resize();}//插入邏輯,也就是在0~size的位置插入元素了 需要后移System.arraycopy(table, index, table, index + 1, size - index);table[index] = element;size++;}//刪除對應下標位置的元素@Overridepublic E remove(int index) {System.out.println( "remove(int index)");//先判斷index是否合法if (index < 0 || index >= size) {throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);}E oldElement = (E) table[index];System.arraycopy(table, index + 1, table, index, size - index - 1);table[--size] = null;return oldElement;}@Overridepublic boolean remove(Object element) {System.out.println( "remove(Object element)");for (int i = 0; i < size; i++) {if (Objects.equals(element, table[i])) {remove(i);return true;}}return false;}//修改下標為index位置的元素為element@Overridepublic E set(E element, int index) {//先判斷index是否合法if (index < 0 || index >= size) {throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);}E oldElement = (E) table[index];table[index] = element;return oldElement;}@Overridepublic E get(int index) {//先判斷index是否合法if (index < 0 || index >= size) {throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);}return (E) table[index];}@Overridepublic int size() {return this.size;}//數組擴容的邏輯private void resize() {//1.5倍擴容Object[] newTable = new Object[table.length + (table.length >> 1)];System.out.println("擴容了,原數組大小" + table.length + ",現在數組大小" + newTable.length);// 從內存的角度把一個數組元素的引用裝到另外一個數組上System.arraycopy(table, 0, newTable, 0, table.length);this.table = newTable;}/*** Returns an iterator over elements of type {@code T}.** @return an Iterator.*/@Overridepublic Iterator<E> iterator() {return new ArrayIterator();}private class ArrayIterator implements Iterator<E> {int cursor = 0;//判斷是否有下一個元素@Overridepublic boolean hasNext() {return cursor != size;}@Overridepublic E next() {if (!hasNext())throw new NoSuchElementException();return (E) table[cursor++];}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/82216.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/82216.shtml
英文地址,請注明出處:http://en.pswp.cn/web/82216.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

每日c/c++題 備戰藍橋杯(Cantor 表)

Cantor 表的探究與實現 在數學中&#xff0c;有理數的可枚舉性是一個令人驚嘆的結論。今天&#xff0c;就讓我們一起深入探討這個經典問題&#xff0c;并分享一段精心編寫的代碼&#xff0c;揭開這一數學奧秘的神秘面紗。 問題背景 在 19 世紀末&#xff0c;偉大的數學家康托…

解決idea與springboot版本問題

遇到以下問題&#xff1a; 1、springboot3.2.0與jdk1.8 提示這個包org.springframework.web.bind.annotation不存在&#xff0c;但是pom已經引入了spring-boot-starter-web 2、Error:Cannot determine path to tools.jar library for 17 (D:/jdk17) 3、Error:(3, 28) java: …

Notepad++找回自動暫存的文件

場景&#xff1a; 當你沒有保存就退出Notepad&#xff0c;下次進來Notepad會自動把你上次編輯的內容顯示出來&#xff0c;以便你繼續編輯。除非你手動關掉當前頁面&#xff0c;這樣Notepad就會刪除掉自動保存的內容。 問題&#xff1a; Notepad會將自動保存的文件地址,打開Note…

yolov12畢設前置知識準備 1

1 什么是目標檢測呢&#xff1f; 目標檢測&#xff08;Object Detection&#xff09;主要用于識別圖像或視頻中特定類型物體的位置&#xff0c;并標注其類別。 簡單來說&#xff0c;就是讓計算機像人類一樣 “看懂” 圖像內容&#xff0c;不僅能識別出物體&#xff08;如人、…

unix/linux source 命令,其內部結構機制

要理解 source (或 .) 命令的內部結構機制,我們需要戴上“操作系統”和“解釋器設計”的眼鏡,深入到 Shell 如何管理其狀態以及如何執行命令的層面。 雖然我們無法直接看到 Shell 內部的 C 代碼(除非我們去閱讀 Bash 或 Zsh 的源碼),但我們可以基于其行為和操作系統的原理…

計算機網絡學習20250528

地址解析協議ARP 實現IP地址和Mac地址的轉換 ARP工作原理&#xff1a; 每臺主機或路由器都有一個ARP表&#xff0c;表項&#xff1a;<IP地址&#xff0c;Mac地址&#xff0c;TTL>&#xff08;TTL一般為20分鐘&#xff09; 主機產生ARP查詢分組&#xff0c;包含源目的IP地…

【Rust】Rust獲取命令行參數以及IO操作

?? 歡迎大家來到景天科技苑?? &#x1f388;&#x1f388; 養成好習慣&#xff0c;先贊后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者簡介&#xff1a;景天科技苑 &#x1f3c6;《頭銜》&#xff1a;大廠架構師&#xff0c;華為云開發者社區專家博主&#xff0c;…

微服務中引入公共攔截器

本文使用的微服務版本為springcloudAlbaba :2021.0.4.0 微服務工程&#xff0c;一般公共的東西都放入一個工程&#xff0c;別的微服務都會引入這個工程&#xff0c;比如common-service,那么就可以在這個工程編寫一個攔截器&#xff1a;&#xff0c;比如&#xff1a; public cla…

Linux SLES 系統的/var/log/下的常見文件及其作用

在 SUSE Linux Enterprise Server&#xff08;SLES&#xff09; 系統中&#xff0c;/var/log/ 目錄是系統日志的集中地&#xff0c;存儲了各種服務、內核、系統消息的日志。以下是一些在 /var/log/ 下常見的日志文件及其功能&#xff1a; &#x1f4c2; 常見日志文件及功能 文…

oracle goldengate同步SQL server到SQL server的實時數據同步

參考文檔 https://docs.oracle.com/en/middleware/goldengate/core/19.1/oggmp/oracle-goldengate-classic-sql-server.html#GUID-948C5BEE-E7A0-4CE2-BE09-F83145677D18 https://docs.oracle.com/en/middleware/goldengate/core/21.3/ggcab/other-programs-and-settings-sql-…

語音轉文字工具

平時工作和學習比較忙&#xff0c;可能沒時間聽講座&#xff0c;只能看回放&#xff0c;回訪也很長&#xff0c;這時&#xff0c;我們可以借助語言轉文字&#xff0c;通過閱讀文字快速了解講座的重點&#xff0c;今天給大家分享一個本人經常用的語言轉文字工具&#xff0c;改工…

硬件實時時鐘(RTC)

硬件實時時鐘&#xff08;RTC&#xff09;詳解 硬件實時時鐘&#xff08;Real-Time Clock&#xff0c;RTC&#xff09;是計算機主板上的一個獨立計時芯片&#xff0c;用于在系統關機后持續記錄時間。它不依賴操作系統&#xff0c;由紐扣電池&#xff08;如CR2032&#xff09;供…

pycharm debug的時候無法debug到指定的位置就停住不動了

報錯大致是這樣的&#xff0c;但是直接run沒有問題&#xff0c;debug就停住不動了 Traceback (most recent call last): File "/home/mapengsen/.pycharm_helpers/pydev/_pydevd_bundle/pydevd_comm.py", line 467, in start_client s.connect((host, port)) Timeou…

Python6.1打卡(day33)

DAY 33 MLP神經網絡的訓練 知識點回顧&#xff1a; 1.PyTorch和cuda的安裝 2.查看顯卡信息的命令行命令&#xff08;cmd中使用&#xff09; 3.cuda的檢查 4.簡單神經網絡的流程 1.數據預處理&#xff08;歸一化、轉換成張量&#xff09; 2.模型的定義 …

NodeJS全棧開發面試題講解——P11消息隊列(MQ)

? 11.1 為什么要用消息隊列&#xff1f;在哪些場景下最適合&#xff1f; ? 作用&#xff1a; 削峰填谷&#xff1a;緩解高并發壓力&#xff0c;異步處理任務&#xff08;如秒殺下單 → MQ → 異步扣庫存&#xff09; 解耦服務&#xff1a;上下游解耦&#xff08;如下單服務…

mysql執行sql語句報錯事務鎖住

報錯情況 1205 - Lock wait timeout exceeded; try restarting transaction先找出長時間運行的事務 SELECT * FROM information_schema.INNODB_TRX ORDER BY trx_started ASC;終止長時間運行的事務 KILL [PROCESS_ID];

C#集合循環刪除某些行

你想要在遍歷集合&#xff08;例如List&#xff09;的同時刪除某些元素時&#xff0c;直接在循環中刪除元素可能會導致問題&#xff0c;因為這可能會改變集合的大小和導致索引問題&#xff1b; 可以用for循環的倒序來刪除&#xff1b; 如果要刪除滿足特定條件的所有元素&…

裂縫儀在線監測裝置:工程安全領域的“實時守衛者”

在基礎設施運維領域&#xff0c;裂縫擴展是威脅建筑結構安全的核心隱患之一。傳統人工巡檢方式存在效率低、時效性差、數據主觀性強等局限&#xff0c;而裂縫儀在線監測裝置通過技術迭代&#xff0c;實現了對結構裂縫的自動化、持續性追蹤&#xff0c;為工程安全評估提供科學依…

Multisim14使用教程詳盡版--(2025最新版)

一、Multisim14前言 1.1、主流電路仿真軟件 1. Multisim:NI開發的SPICE標準仿真工具,支持模擬/數字電路混合仿真,內置豐富的元件庫和虛擬儀器(示波器、頻譜儀等),適合教學和競賽設計。官網:艾默生旗下測試和測量系統 - NI。 2. LTspice XVII:ADI旗下免費高性能SPICE仿…

深度學習篇---人臉識別中的face-recognition庫和深度學習

深度學習方法和使用 Python 的face_recognition庫進行人臉識別在技術原理、實現方式和應用場景上有顯著區別&#xff0c;以下從多個維度對比分析&#xff1a; 一、技術原理 1. 深度學習方法 核心邏輯&#xff1a;基于神經網絡&#xff08;如卷積神經網絡 CNN&#xff09;構建…