Java - 从 LinkedList 中删除一个元素,除了第一个

标签 java linked-list singly-linked-list

我是 Java 新手。

我创建了一个方法,它将从 LinkedList 中删除除第一个元素之外的元素。这个想法是,如果 LinkedList 的元素数据(以整数形式)与参数匹配,则 boolean 值将设置为 true。一旦 boolean 值设置为 true,它将删除所有也与初始元素匹配的元素。

现在是问题。例如,如果我要从此 LinkedList 中删除除第一个之外的 5 个:

5 5 5 6 5 7 8 9

我会得到这样的结果:

5 5 6 7 8 9

如您所见,它没有删除第二个位置上的 5。我的代码有什么问题吗?

顺便说一下代码

public void append(int data) {
    Node newNode = new Node(data);
    if (head == null) {
        head = new Node(data);
        return;
    }

    Node lastNode = head;
    while (lastNode.next != null) {
        lastNode = lastNode.next;
    }

    lastNode.next = newNode;
    return;
}

public void insert(int data) {
    Node newData = new Node(data);
    newData.next = head;
    head = newData;
}

public void removeExceptFirst(int dataValue) { //The mentioned method
    boolean duplicate = false;
    Node currentNode = head;
    while (currentNode.next != null) {
        int value = currentNode.next.data;
        if (value == dataValue) {
            if (!duplicate) {
                duplicate = true;
                currentNode = currentNode.next;
            } else {
                currentNode.next = currentNode.next.next;
            }
        } else {
        currentNode = currentNode.next;
        }
    }
    return;
}

最佳答案

这里的问题是

if (!duplicate) {
     duplicate = true;
     currentNode = currentNode.next;
} 

您正在标记 duplicate = true 并立即分配“currentNode = currentNode.next;” 由于此引用正在保留下一个节点 所以

1. Put the condition outside of the loop to check whether the head element itself is 
   that node, if->yes mark isDuplicate = true and proceed in the loop.
2. Inside the loop check afterward and then assign the next node.

希望这能奏效

关于Java - 从 LinkedList 中删除一个元素,除了第一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55094847/

相关文章:

c - C语言中的简单链表程序

c - 单链接列表添加 - 无限循环

在 C 中使用链表时控制内存

c++ - 采访 : Summing numbers in two linked lists

objective-c - 如何使用 Objective C 反转单链表

c - 链表在打印时仅显示第一个节点元素

java - Struts2如何在没有线程的情况下获得性能?

java - 如何在写入 Java 字符串之前检查它是否适合 Cassandra TEXT 列?

java - 哪些异常需要方法的 throws 语句?

java - 这种情况会导致内存泄漏吗?