首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java -从LinkedList中删除除first以外的元素

Java -从LinkedList中删除除first以外的元素
EN

Stack Overflow用户
提问于 2019-03-11 11:26:53
回答 3查看 338关注 0票数 2

我是Java新手。

我已经创建了一个方法,它将从LinkedList中删除除第一个元素之外的元素。如果LinkedList的元素数据(在Integer中)与参数匹配,则布尔值将被设置为true。一旦布尔值设置为true,它将删除所有与初始元素匹配的元素。

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

5 5 5 6 5 7 8 9

我会得到这样的结果:

5 5 6 7 8 9

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

顺便说一句,这是代码

代码语言:javascript
运行
复制
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;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-11 14:16:26

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

代码语言:javascript
运行
复制
    Node currentNode = head;

使用

代码语言:javascript
运行
复制
    Node currentNode = new Node();
    currentNode.next = head;
票数 0
EN

Stack Overflow用户

发布于 2019-03-11 17:44:26

这里的问题是

代码语言:javascript
运行
复制
if (!duplicate) {
     duplicate = true;
     currentNode = currentNode.next;
} 

您正在标记duplicate = true并立即赋值"currentNode = currentNode.next;“,因为此引用将保留下一个节点,因此

代码语言:javascript
运行
复制
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.

希望这能行得通

票数 1
EN

Stack Overflow用户

发布于 2019-03-11 16:58:24

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

代码语言:javascript
运行
复制
if (!duplicate) {
    duplicate = true;
    currentNode = currentNode.next;
     head.next= currentNode.next;
}else {
    currentNode.next = currentNode.next.next;
    currentNode = currentNode.next;
    head.next = currentNode;  }

`

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55094847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档