【问题标题】:Java - Removing an element from LinkedList except firstJava - 从 LinkedList 中删除一个元素,除了第一个
【发布时间】:2019-08-01 08:28:48
【问题描述】:

我是 Java 新手。

我创建了一个方法,它将从 LinkedList 中删除除第一个之外的元素。这个想法是,如果 LinkedList 的元素数据(在 Integer 中)与参数匹配,则布尔值将设置为 true。一旦布尔值设置为 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;
}

【问题讨论】:

  • 如果你想防止重复,有什么原因不能使用LinkedHashSet
  • @D.B.这可能有效,但我试图在不使用它的情况下删除重复项

标签: java linked-list singly-linked-list


【解决方案1】:

您跳过了头节点。尝试替换

    Node currentNode = head;

    Node currentNode = new Node();
    currentNode.next = head;

【讨论】:

  • 谢谢!这个工作正常。我还创建了一个新的 LinkedList,它是原始版本的反转版本,并且仍然有效。
【解决方案2】:

您应该更新当前节点引用以及 head->next 应该在删除节点后指向当前节点。 试试下面的代码:

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

`

【讨论】:

    【解决方案3】:

    问题出在

    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.
    

    希望这应该工作

    【讨论】:

    • 它工作了,但另一个问题出现了我在反向的 LinkedList 上尝试了新方法,即:9 8 7 5 6 5 5 5。虽然原始的 LinkedList 工作正常,但反向的已经删除了所有5 就可以了,结果为:9 8 7 6。我尝试了 lauthu 的解决方案,它有效
    猜你喜欢
    • 2017-02-25
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    相关资源
    最近更新 更多