gpt4 book ai didi

java - 如何删除链表java中的所有偶数

转载 作者:行者123 更新时间:2023-11-30 06:09:09 26 4
gpt4 key购买 nike

如何删除java中链表中的所有事件?其他类似的问题对我没有帮助。我有一个可能的解决方案,但它似乎太复杂了。我不确定它是否有效。

public class Node {
public int value;
public Node next;
public Node (int val) {
value = val;
}
public Node removeNode (Node root) {
if (root == null || (root.next == null && isOdd(root.value))) {
return null;
}
Node deep = root;
while (deep.next != null) {
deep = deep.next;
}
if (isOdd(deep.value)) {
for (Node x = root; x != null; x = x.next) {
if (isOdd(x.next.value)) {
x.next = x.next.next;
}
}
} else {
for (Node x = root; x.next != null; x = x.next) {
if (isOdd(x.next.value)) {
x.next = x.next.next;
}
}
}
if (isOdd(root.value)) {
root = root.next;
}
return root;
}
public boolean isOdd (int val) {
return (val % 2 == 1);
}

我该如何改进这个解决方案?

最佳答案

首先:remove 方法应该位于您的 LinkedList 类中,而不是位于 Node 类本身中!

之后,删除偶数就很容易了:

public class LinkedList {
private Node root;

public void removeEvens() {
if (root == null) return;

// removing all even nodes after the root
Node prev = root;
while (prev.next != null) {
if (isEven(prev.next))
prev.next = prev.next.next; // next is even: delete it
else
prev = prev.next; // next is not even: proceed
}

// delete root if it's even
if (isEven(root))
root = root.next;
}

private boolean isEven(Node node) {
return node.value % 2 == 0;
}
}

关于java - 如何删除链表java中的所有偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556779/

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