• 数据结构之单链表的模拟实现


      💕"你笑的次数越多越好,因为你只有用笑才能不怀恶意地消灭罪恶。"💕

    作者:Mylvzi 

     文章主要内容:数据结构之单链表的模拟实现 

    一.前言:
     

    在上个顺序表的博客结尾针对ArrayList的缺陷留了一个思考题

    大家可以去再看一下顺序表这篇博客https://blog.csdn.net/Mylvzi/article/details/133896470?spm=1001.2014.3001.5501

      因为ArrayList的底层是一段连续内存的空间,进行插入/删除操作的开销很大,因此ArrayList不适合用于"需要大量添加/删除数据的场景",因此Java中又引入了LinkedList,即链表结构

    二.链表

    1.链表的概念及结构

      链表是物理地址不连续的线性表,逻辑顺序是通过"链条"连接起来的

    可以将链表想象成拉着很多节车厢的火车

    注意:
    1.链表是由一个个结点(Node)组成的,每个结点都是从堆上申请的

    2.堆为每个结点分配内存地址,分配时是随机的,所以链表的物理结构是不连续的

    链表的分类:

    按照不同的性质可以有多种分类方法:

    • 按照是否有"头节点":带头和不带头
    • 按照是否循环:循环和不循环
    • 按照链表逻辑的方向:单向和双向

     

    综上,链表可分为2 * 2 * 2 = 8种,在这里我们只需重点掌握两种链表即可

    • 无头单项非循环链表  面试常考
    • 无头双向非循环链表  Java中LinkedList的底层就是一个无头双向非循环链表

    注意:这里说的"有无头节点"中的头节点不属于链表中的有效数据,他更像是一个“傀儡节点”,仅仅作为前驱使用

    三.无头单向非循环链表的实现

    1.链表的结构

    1. // 定义结点
    2. static class ListNode {
    3. int val;// 结点存储的数据
    4. ListNode next;// 保存下一个结点的地址
    5. public ListNode(int val) {
    6. this.val = val;
    7. }
    8. }
    9. // 定义头节点
    10. public ListNode head = null;

    2.链表的插入

    因为链表的物理地址并不是连续的,所以我们插入数据的位置是多样性的,总的来说可以分为三种

    • 头插法:addFirst
    • 尾插法:addLast
    • 任意位置插入:addIndex

    1.头插法

      头插法及创建一个新的结点,将此结点插入到第一个结点之前

    1. public void addFirst(int data) {
    2. ListNode newNode = new ListNode(data);
    3. // 头插法不需要考虑链表是否为空
    4. newNode.next = head;
    5. head = newNode;
    6. }

    注意:

    在链表中插入/删除数据时,最重要的一点是记得保存"下一节点",往往是先连接后面的结点,在进行其他的操作(如果不先连接后面的结点就会损失后面的所有节点火车一节车厢断开,则后面的车厢都断开了)

    2.尾插法

    尾插法即在链表的末尾添加一个新的结点

    1. public void addLast(int data) {
    2. ListNode newNode = new ListNode(data);
    3. // 如果为空 链表中没有一个节点 直接插入
    4. if(head == null) {
    5. head = newNode;
    6. return;
    7. }
    8. ListNode cur = head;
    9. // 让cur走到链表的最后一个节点
    10. while (cur.next != null) {
    11. cur = cur.next;
    12. }
    13. cur.next = newNode;
    14. }

    3.任意位置插入

    给指定的位置index,在指定位置插入一个节点(第一节点对应的index为0)

    1. public void addIndex(int index,int data) {
    2. // 先检查index是否合法
    3. if(index < 0 || index > size()) {
    4. throw new posOutOfBoundException(index + "位置不合法");
    5. }
    6. if (index == 0) addFirst(data);
    7. if (index == size()) addLast(data);
    8. // 让cur走到要删除结点的前驱节点 走index - 1步
    9. ListNode cur = head;
    10. for (int i = 0; i < index-1; i++) {
    11. cur = cur.next;
    12. }
    13. ListNode newNode = new ListNode(data);
    14. newNode.next = cur.next;
    15. cur.next = newNode;
    16. }

    3.查找是否包含关键字key的结点

    1. // 判断是否包含
    2. public boolean contains(int key) {
    3. ListNode cur = head;
    4. while (cur != null) {
    5. if (cur.val == key) {
    6. return true;
    7. }
    8. cur = cur.next;
    9. }
    10. return false;
    11. }

    4.求链表的长度

    1. // 返回长度
    2. public int size() {
    3. ListNode cur = head;
    4. int cnt = 0;// 设置计数器
    5. while (cur != null) {
    6. cnt++;
    7. cur = cur.next;
    8. }
    9. return cnt;
    10. }

    5. 删除第一次出现关键字为key的节点

     要进行此删除操作,关键还是要在删除对应节点之后仍然连接之后的结点

    1. public void remove(int key) {
    2. if(head == null) {
    3. throw new RuntimeException("链表为空 无法删除");
    4. }
    5. if (head.val == key) {
    6. head = head.next;
    7. return;
    8. }
    9. // 让cur走到要删除节点的前驱节点
    10. ListNode cur = findPrevNode(key);
    11. if(cur == null) {
    12. System.out.println("没有你要删除的结点");
    13. return;
    14. }
    15. cur.next = cur.next.next;
    16. }
    17. // 找要删除结点的前驱结点
    18. private ListNode findPrevNode(int key) {
    19. ListNode cur = head;
    20. while (cur != null) {
    21. if (cur.next.val == key) {
    22. return cur;
    23. }
    24. cur = cur.next;
    25. }
    26. return null;
    27. }

    6.删除所有值为key的节点

    1. public void removeAll(int key) {
    2. if(head == null) {
    3. throw new RuntimeException("链表为空 无法删除");
    4. }
    5. // 处理头节点是key的情况
    6. while (head.val == key) {
    7. head = head.next;
    8. }
    9. // 设置两个结点 前驱节点prev 和用于遍历的结点cur
    10. ListNode prev = head;
    11. ListNode cur = head.next;
    12. while (cur != null) {
    13. // 等于 进行删除
    14. if (cur.val == key) {
    15. prev.next = cur.next;
    16. cur = cur.next;
    17. continue;
    18. }
    19. prev = prev.next;
    20. cur = cur.next;
    21. }
    22. }

    注意考虑当头节点是要删除的结点 

    7.链表的打印

    1. // 打印链表
    2. public void display() {
    3. // 要始终保持head结点是头节点 此处使用一个临时结点cur用于遍历整个链表
    4. ListNode cur = head;
    5. while (cur != null) {
    6. System.out.print(cur.val);
    7. cur = cur.next;
    8. }
    9. }

     四.LinkedList

    1.什么是LinkedList

      LinkedList是Java中使用双向链表实现的一中数据结构,每个节点都含有三个属性:

    • elem:存储元素的值
    • next:保存当前节点的下一个结点
    • prev:保存当前结点的上一个结点

    在集合框架中,LinkedList也实现了List接口

    说明:

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

    2.LinkedList适合用于大量进行数据增加/删除的操作

    2.LinkedList的模拟实现

    1.LinkedList的结构

    LinkedList是一个双向的链表,且有两个"标记结点"head,last,分别用于标记链表的头/尾

    2.代码实现 

    1. public class MyLinkedList {
    2. static class ListNode {
    3. private int data;
    4. private ListNode prev;
    5. private ListNode next;
    6. public ListNode(int data) {
    7. this.data = data;
    8. }
    9. }
    10. public ListNode head;
    11. public ListNode last;
    12. /**
    13. * 前三个方法和prev没关系
    14. * 只需遍历整个链表即可
    15. * @return
    16. */
    17. //得到单链表的长度
    18. public int size(){
    19. int cnt = 0;
    20. ListNode cur = head;
    21. while (cur != null) {
    22. cnt++;
    23. cur = cur.next;
    24. }
    25. return cnt;
    26. }
    27. // 打印链表
    28. public void display(){
    29. ListNode cur = head;
    30. while (cur != null) {
    31. System.out.print(cur.data + " ");
    32. cur = cur.next;
    33. }
    34. System.out.println();
    35. }
    36. //查找是否包含关键字key是否在单链表当中
    37. public boolean contains(int key){
    38. ListNode cur = head;
    39. while (cur != null) {
    40. if (cur.data == key) {
    41. return true;
    42. }
    43. cur = cur.next;
    44. }
    45. System.out.println("链表不包含该元素");
    46. return false;
    47. }
    48. //头插法
    49. public void addFirst(int data){
    50. ListNode node = new ListNode(data);
    51. // 为空,直接赋值
    52. if (head == null) {
    53. head = last = node;
    54. }else {
    55. node.next = head;
    56. head.prev = node;
    57. head = node;
    58. }
    59. }
    60. //尾插法 最方便的一集 因为本来就有尾结点
    61. public void addLast(int data){
    62. ListNode node = new ListNode(data);
    63. // 为空,直接赋值
    64. if (head == null) {
    65. head = last = node;
    66. }else {
    67. last.next = node;
    68. node.prev = last;
    69. last = node;
    70. }
    71. }
    72. //任意位置插入,第一个数据节点为0号下标
    73. public void addIndex(int index,int data){
    74. if(index<0 || index>size()) {
    75. throw new RuntimeException(index + "位置异常");
    76. }
    77. if (index == 0) {
    78. addFirst(data);
    79. return;
    80. }
    81. if(index == size()){
    82. addLast(data);
    83. return;
    84. }
    85. ListNode cur = searchIndex(index);
    86. ListNode node = new ListNode(data);
    87. // 插入 对于单链表来说需要cur走到Index位置的前一个结点 而双向链表不需要 直接走到index位置的结点即可
    88. // 在index位置的插入都是先绑定后面的
    89. node.next = cur;
    90. cur.prev.next = node;
    91. // 这两行的顺序不能改变
    92. node.prev = cur.prev;
    93. cur.prev = node;
    94. }
    95. private ListNode searchIndex(int index) {
    96. ListNode cur = head;
    97. while (index > 0) {
    98. cur = cur.next;
    99. index--;
    100. }
    101. return cur;
    102. }
    103. /**
    104. * 我写的这个删除的代码将寻找data==Key的这个过程封装成一个方法 思路很好 但是不利于写删除所有的key值的方法
    105. * 因为想要删除所有的key值,不可避免的是要遍历整个链表,而不是得到某一个节点
    106. * @param key
    107. * @return
    108. */
    109. /* //删除第一次出现关键字为key的节点
    110. public void remove(int key){
    111. // 不能这样写,因为要求的是删除第一次出现的key
    112. // if(last.data == key) {
    113. // last = last.prev;
    114. // last.next = null;
    115. // return;
    116. // }
    117. // 使cur为data为key的结点
    118. ListNode cur = findIndexOf(key);
    119. if (cur == null) {
    120. System.out.println("没有你要删除的结点");
    121. return;
    122. }
    123. if (cur == head) {
    124. head = head.next;
    125. if (head != null) {
    126. head.prev = null;
    127. }else {
    128. // 处理只有一个结点的情况 head直接为空了 此时只需把last也置空即可
    129. last = null;
    130. }
    131. }else {
    132. // 处理中间结点和尾巴结点 尾巴结点要单独处理(后继为null)
    133. if (cur.next != null) {
    134. cur.prev.next = cur.next;
    135. cur.next.prev = cur.prev;
    136. }else {
    137. cur.prev.next = null;
    138. last = cur.prev;
    139. }
    140. }
    141. }
    142. private ListNode findIndexOf(int key) {
    143. ListNode cur = head;
    144. while (cur != null) {
    145. if (cur.data == key) {
    146. return cur;
    147. }
    148. cur = cur.next;
    149. }
    150. return null;
    151. }*/
    152. /**
    153. * 重写remove方法
    154. * @param key
    155. * @return
    156. */
    157. public void remove(int key) {
    158. ListNode cur = head;
    159. while (cur != null) {
    160. if (cur.data == key) {
    161. // 等于key也要分两种情况
    162. if (cur == head) {
    163. head = head.next;
    164. if (head == null) {
    165. last = null;
    166. }else {
    167. head.prev = null;
    168. }
    169. }else {
    170. // 处理中间结点和尾结点
    171. if (cur.next != null) {
    172. cur.prev.next = cur.next;
    173. cur.next.prev = cur.prev;
    174. }else {
    175. cur.prev.next = null;
    176. last = cur.prev;
    177. }
    178. }
    179. return;
    180. }else {
    181. cur = cur.next;
    182. }
    183. }
    184. }
    185. //删除所有值为key的节点
    186. public void removeAllKey(int key){
    187. ListNode cur = head;
    188. while (cur != null) {
    189. if (cur.data == key) {
    190. // 等于key也要分两种情况
    191. if (cur == head) {
    192. head = head.next;
    193. if (head == null) {
    194. last = null;
    195. }else {
    196. head.prev = null;
    197. }
    198. }else {
    199. // 处理中间结点和尾结点
    200. if (cur.next != null) {
    201. cur.prev.next = cur.next;
    202. cur.next.prev = cur.prev;
    203. }else {
    204. cur.prev.next = null;
    205. last = cur.prev;
    206. }
    207. }
    208. cur = cur.next;
    209. //return;
    210. }else {
    211. cur = cur.next;
    212. }
    213. }
    214. }
    215. public void clear(){
    216. ListNode cur = head;
    217. while (cur != null) {
    218. ListNode curNext = cur.next;
    219. cur.prev = null;
    220. cur.next = null;
    221. cur = cur.next;
    222. }
    223. // 头尾结点要单独置空
    224. head = null;
    225. last = null;
    226. // // 把每一个链表都指控
    227. // ListNode cur = head;
    228. // while (cur != null) {
    229. // cur.prev = null;
    230. // cur = cur.next;
    231. // if (cur != null) {
    232. // cur.prev.next = null;
    233. // }
    234. // }
    235. }
    236. }

    3.LinkedList的使用

    1.构造方法
    • LinkedList() 无参构造
    • public LinkedList(Collection c) 使用其他集合容器中元素构造List
    1. // 无参的构造方法
    2. public LinkedList() {
    3. }
    4. // 使用其他集合来构建一个链表
    5. public LinkedList(Collection c) {
    6. this();// 调用上面的构造方法
    7. addAll(c);// 将集合c中的所有元素填入到创建的链表中
    8. }
    2.其他方法
    1.add

    boolean add(E e) 尾插 e

    1. // This method is equivalent to addLast. 这个方法和addLast是等价的
    2. public boolean add(E e) {
    3. linkLast(e);
    4. return true;
    5. }
    6. // 尾插
    7. void linkLast(E e) {
    8. final LinkedList.Node l = last;// 让l指向最后一个结点
    9. // 创建一个新的结点
    10. final LinkedList.Node newNode = new LinkedList.Node<>(l, e, null);
    11. last = newNode;
    12. if (l == null)
    13. first = newNode;
    14. else
    15. l.next = newNode;
    16. size++;
    17. modCount++;// 用于记录集合被修改的次数
    18. }

     void add(int index, E element) 将 e 插入到 index 位置

    1. public void add(int index, E element) {
    2. checkPositionIndex(index);// 检查index是否合法
    3. // 尾插
    4. if (index == size)
    5. linkLast(element);
    6. else
    7. linkBefore(element, node(index));
    8. }
    9. // Inserts element e before non-null Node succ. 在succ之前添加一个非空的结点e
    10. void linkBefore(E e, LinkedList.Node succ) {
    11. // assert succ != null;
    12. // 设置pred为succ的前驱节点
    13. final LinkedList.Node pred = succ.prev;
    14. final LinkedList.Node newNode = new LinkedList.Node<>(pred, e, succ);
    15. succ.prev = newNode;
    16. if (pred == null)
    17. first = newNode;
    18. else
    19. pred.next = newNode;
    20. size++;
    21. modCount++;
    22. }

    boolean addAll(Collection c) 尾插 c 中的元素

    1. public boolean addAll(Collection c) {
    2. return addAll(size, c);
    3. }
    4. public boolean addAll(int index, Collection c) {
    5. checkPositionIndex(index);
    6. // 将集合c转变为数组 并求出他的长度
    7. Object[] a = c.toArray();
    8. int numNew = a.length;
    9. if (numNew == 0)
    10. return false;
    11. LinkedList.Node pred, succ;
    12. if (index == size) {
    13. // 对list进行尾插集合c
    14. succ = null;
    15. pred = last;
    16. } else {
    17. // 在指定位置的list中进行c集合的插入
    18. succ = node(index);
    19. pred = succ.prev;
    20. }
    21. // 遍历集合 进行插入
    22. for (Object o : a) {
    23. @SuppressWarnings("unchecked") E e = (E) o;
    24. LinkedList.Node newNode = new LinkedList.Node<>(pred, e, null);
    25. if (pred == null)
    26. first = newNode;
    27. else
    28. pred.next = newNode;
    29. pred = newNode;
    30. }
    31. // 将新加入的结点和原来的结点连接起来
    32. if (succ == null) {
    33. // 此处处理的是尾插
    34. last = pred;
    35. } else {
    36. // 处理在指定位置的插入
    37. pred.next = succ;
    38. succ.prev = pred;
    39. }
    40. size += numNew;
    41. modCount++;
    42. return true;
    43. }
    2.remove

     E remove(int index) 删除 index 位置元素

    1. public E remove(int index) {
    2. checkElementIndex(index);
    3. return unlink(node(index));
    4. }
    5. E unlink(LinkedList.Node x) {
    6. // assert x != null;
    7. final E element = x.item;
    8. final LinkedList.Node next = x.next;
    9. final LinkedList.Node prev = x.prev;
    10. // 先处理x.prev
    11. if (prev == null) {
    12. // 要删除的结点为头结点 直接让x的下一个结点作为头结点
    13. first = next;
    14. } else {
    15. // 不是头结点 连接x的下一个节点
    16. prev.next = next;
    17. x.prev = null;
    18. }
    19. // 处理x.next
    20. if (next == null) {
    21. // 要删除的结点是尾结点
    22. last = prev;
    23. } else {
    24. next.prev = prev;
    25. x.next = null;
    26. }
    27. x.item = null;
    28. size--;
    29. modCount++;
    30. return element;
    31. }

    以下操作都十分简单,读者可自行查阅使用,这里不做过多的介绍 

    3.get

    E get(int index) 获取下标 index 位置元素

    4.set

     E set(int index, E element) 将下标 index 位置元素设置为 element

    5.contains

     boolean contains(Object o) 判断 o 是否在线性表中

    6.indexOf

    int indexOf(Object o) 返回第一个 o 所在下标 

    7.subList

     List subList(int fromIndex, int toIndex) 截取部分 list

     3. LinkedList的遍历

    LinkedList的遍历的遍历一般有两种遍历方式

    • 迭代器
    • for each循环
    1. public static void main(String[] args) {
    2. LinkedList list = new LinkedList<>();
    3. list.add(1); // add(elem): 表示尾插
    4. list.add(2);
    5. list.add(3);
    6. list.add(4);
    7. list.add(5);
    8. list.add(6);
    9. list.add(7);
    10. // for each循环遍历
    11. for (Integer i : list) {
    12. System.out.print(i + " ");
    13. }
    14. // 迭代器
    15. Iterator iterator = list.iterator();
    16. while(iterator.hasNext()){
    17. System.out.println(iterator.next());
    18. }
    19. }

    五. ArrayList和LinkedList的区别

    1. 存储空间:ArrayList物理地址连续        LinkedList物理地址不连续
    2. 随机访问(RandomAccess接口):ArrayList支持随机访问    LinkedList不支持
    3. 头插:ArrayList需要挪动数据    LinkedList不需要挪动数据
    4. 扩容:ArrayList空间不够需要使用grow进行1.5倍扩容    LinkedList没有容量的概念
    5. 应用场景:ArrayList频繁的查询    LinkedList频繁的进行数据的删除/插入
  • 相关阅读:
    Python中的变量是什么类型?
    牛哇!MySQL中的日志“binlog”的三种格式这么好玩
    拼多多笔试
    当老板一定要学会花钱去赚钱
    基于Springboot的租房网站
    【数据结构】—— 队列基础知识以及数组模拟队列的分析、演示及优化
    Simple WPF: WPF 透明窗体和鼠标事件穿透
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver报错
    数据仓库模式之详解 Inmon 和 Kimball
    GaussDB数据库SQL系列-LOCK TABLE
  • 原文地址:https://blog.csdn.net/Mylvzi/article/details/133896432