gpt4 book ai didi

java - Java中向单链表添加元素

转载 作者:行者123 更新时间:2023-12-02 03:18:32 25 4
gpt4 key购买 nike

我正在用 Java 实现一个单链表。我不喜欢这段代码的是每次添加元素时都需要检查 if (head.next == null) 。但该条件仅在添加第一个元素时满足一次。

有没有办法在没有这样的条件的情况下实现单链非循环列表?

package sample;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class SinglyLinkedList<T> implements Iterable<T> {

private Node<T> head = new Node<T>(null);
private Node<T> last = null;

public SinglyLinkedList(T... elements) {
addAll(elements);
}

public void add(T element) {
if (head.next == null) {
head.next = new Node<T>(element);
last = head.next;
} else {
Node<T> newNode = new Node<T>(element);
last.next = newNode;
last = last.next;
}
}

public void addAll(T... elements) {
for (T element : elements) {
add(element);
}
}

@Override
public String toString() {
Iterator<T> iterator = iterator();
if (!iterator.hasNext()) {
return "[]";
}
StringBuilder builder = new StringBuilder();
builder.append("[");
while (iterator.hasNext()) {
T element = iterator.next();
builder.append(element);
if (!iterator.hasNext()) {
return builder.append("]").toString();
}
builder.append(", ");
}
return builder.toString();
}

@Override
public Iterator<T> iterator() {
return new Iterator<T>() {

Node<T> current = head;

@Override
public boolean hasNext() {
return current.next != null;
}

@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Node<T> temp = current;
current = current.next;
return temp.next.element;
}

};
}

private static class Node<T> {

private Node<T> next;
private T element;

Node(T element) {
this.element = element;
}

@Override
public String toString() {
return element.toString();
}
}
}

最佳答案

您可以将 last 初始化为指向 head,然后您的 if 是多余的:

private Node<T> head = new Node<T>(null);
private Node<T> last = head;

public void add(T element) {
Node<T> newNode = new Node<T>(element);
last.next = newNode;
last = last.next;
}

关于java - Java中向单链表添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39936260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com