java - 在 linkedList 的末尾添加一个元素

标签 java linked-list

<分区>

任务是使用 boolean 值在 linkedList 的末尾附加一个元素

/**
* Appends the specified element to the end of this list
* @param element element to add to the list
* @return true
* @throws NullPointerException when element is null
*/

我的解决方案

public boolean add(T element) {
    ListNode newElement = new ListNode (element);
    while (cur.link == !null) {
        cur = cur.link;
        cur.link = newElement(element, null); 
        if (cur==null) {
            throw new NullPointerException;
        }
    }
    return true;
}

在更正我的代码时需要帮助。

最佳答案

您需要确保 cur 变量已初始化为某些内容,并将以下行更改为使用 != 而不是 == !

while (cur.link != null) {

这将有助于编译 @rpax 完成了繁重的工作。

关于java - 在 linkedList 的末尾添加一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23286539/

相关文章:

java - JMeter javax.net.ssl.SSLHandshakeException 间歇性

java - Android CalendarView 年份文本颜色

python - 当我们将 [1] 放在函数末尾和元组末尾时,它是什么意思?

c - 在 C 中有效地添加两个链表

c - 这个将元素添加到链表的函数有什么问题?

c++ - 将节点插入双向链表

java - 如何从 gson 生成的字符串中转义或删除 "\"?

java - Java中如何显示登录后的用户名?

Java Jpanels 和渐变背景

java - 按顺序、向前和向后打印 LinkedList 列表