diff --git a/data-structures/src/main/java/array_list/ArrayList.java b/data-structures/src/main/java/array_list/ArrayList.java index fb1008e..3c8dc95 100644 --- a/data-structures/src/main/java/array_list/ArrayList.java +++ b/data-structures/src/main/java/array_list/ArrayList.java @@ -45,10 +45,13 @@ public boolean add(E e) { // 判断扩容操作 if (minCapacity - elementData.length > 0) { int oldCapacity = elementData.length; + // 扩容为原容量的 1.5 倍 int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) { + // 如果计算得到的新容量小于 minCapacity,则直接使用 minCapacity newCapacity = minCapacity; } + // 扩容数组 elementData = Arrays.copyOf(elementData, newCapacity); } // 添加元素 diff --git a/data-structures/src/main/java/linked_list/LinkedList.java b/data-structures/src/main/java/linked_list/LinkedList.java index f41077d..3371b05 100644 --- a/data-structures/src/main/java/linked_list/LinkedList.java +++ b/data-structures/src/main/java/linked_list/LinkedList.java @@ -1,5 +1,7 @@ package linked_list; +import java.util.Objects; + /** * @author 小傅哥,微信:fustack * @description 实现双向链表 @@ -60,22 +62,22 @@ public boolean addLast(E e) { @Override public boolean remove(Object o) { - if (o == null) { - for (Node x = first; x != null; x = x.next) { - if (x.item == null) { - unlink(x); - return true; - } - } - } else { - for (Node x = first; x != null; x = x.next) { - if (o.equals(x.item)) { - unlink(x); - return true; - } + // 在循环外部声明变量,用于记录是否找到匹配项 + boolean found = false; + + // 遍历链表 + Node x = first; + while (x != null) { + if (Objects.equals(o, x.item)) { + // 找到匹配项,调用 unlink 方法移除节点 + unlink(x); + found = true; + break; // 找到匹配项后立即跳出循环 } + x = x.next; } - return false; + + return found; } E unlink(Node x) { @@ -125,6 +127,7 @@ public void printLinkList() { Node node(int index) { if (index < (size >> 1)) { + // 如果索引小于链表长度的一半,则从头部开始遍历链表 Node x = first; for (int i = 0; i < index; i++) x = x.next;