Skip to content

添加注释 #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions data-structures/src/main/java/array_list/ArrayList.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
// 添加元素
Expand Down
31 changes: 17 additions & 14 deletions data-structures/src/main/java/linked_list/LinkedList.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package linked_list;

import java.util.Objects;

/**
* @author 小傅哥,微信:fustack
* @description 实现双向链表
Expand Down Expand Up @@ -60,22 +62,22 @@ public boolean addLast(E e) {

@Override
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
// 在循环外部声明变量,用于记录是否找到匹配项
boolean found = false;

// 遍历链表
Node<E> 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<E> x) {
Expand Down Expand Up @@ -125,6 +127,7 @@ public void printLinkList() {

Node<E> node(int index) {
if (index < (size >> 1)) {
// 如果索引小于链表长度的一半,则从头部开始遍历链表
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
Expand Down