如何删除链表java中的所有evens

时间:2016-07-24 21:05:11

标签: java nodes

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

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);
}

如何改进此解决方案?

2 个答案:

答案 0 :(得分:5)

首先: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;
    }
}

答案 1 :(得分:0)

您可以在根节点之前添加元素。在这种情况下,您不必为检查根节点编写代码。

public class Node {
    public int value;
    public Node next;

    public Node(){}

    public Node (int val) {
        value = val;
    }

    public static Node removeEvens (Node root) {
        Node head = new Node();
        head.next = root;

        for (Node node = head; node.next!=null; node=node.next) 
           if (isEven(node.next))
                node.next = node.next.next;

        return head.next;
    }

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