从不在尾节点工作的链表中删除偶数?

时间:2015-01-31 18:54:26

标签: java data-structures linked-list nodelist

void deleteEven() {
        boolean con = false;
        Node add;
        Node move;
        move = head;
        if (move.data % 2 == 0) {
            head = move.next;
            con = true;
        }
        add = move;
        move = move.next;
        while (move != null) {
            if (move.data % 2 == 0 ) {
                add.next = move.next;
                con = true;
            }
            add = move;
            move = move.next;
        }
        if (!con)
            System.out.println("No even numbers in list");
    }

它适用于除尾部以外的每个节点。 如果链表是[5,4,3,2,2] 结果是[5,3,2] 如何解决?

2 个答案:

答案 0 :(得分:1)

问题不在于尾节点。问题在于连续两个偶数节点,而不管它们在列表中的位置。当前节点是偶数时,即使您刚刚删除它,也会将指针移动到前一个节点(add)到当前节点。对于第二个偶数节点,您的add.next = move.next语句会更改next您刚删除的节点。

最简单的解决方案是,如果节点不均匀,则仅移动add

if (move.data % 2 == 1) {
    add.next = move.next;
    con = true;
} else {
    add = move.next;
}

你可以通过完全摆脱add并在move之前查看一个节点来简化你的代码:

while (move.next != null) {
    if (move.next.data % 2 == 0) {
        move.next = move.next.next;
        con = true;
    } else {
        move = move.next;
    }
}

为您编写一个程序提示:在尝试诊断问题之前有几个测试用例。我发现基于少量测试用例很容易得出错误的结论,并且通常扩大范围会使问题更加清晰。这是测试驱动开发的工作原理之一(很多)。

答案 1 :(得分:0)

让我们创建服务节点来附加其他节点。

然后遍历列表并复制新列表中的引用(不创建新节点):

void deleteEven() {
    Node tmpHead = new Node(0, null);
    Node tmpCopy = tmpHead;
    Node tmp = head;
    while (tmp != null) {
        if (tmp.data % 2 == 1) {
            tmpCopy.next = tmp;
            tmpCopy = tmpCopy.next;
        }
        tmp = tmp.next;
    }
    tmpCopy.next = null;
    head = tmpHead.next;
}

假设Node是什么:

class Node {
    int data;
    Node next;

    public Node(int data, Node next) {
        this.data = data;
        this.next = next;
    }
}