从java中的链接列表中删除最后一个节点

时间:2014-04-22 15:33:35

标签: java

是删除最后一个节点的方法。

public void delete_at_end(int data) {
    Node ppre;
    if (head== null) {
        throw new RuntimeException("cannot delete");
    } else {
        if (head == last) {
            head = null;
            last = null;

         } else {
            ppre = head;
            while (ppre.next != null && ppre.data!=data) {
                ppre = ppre.next;
            }
            last=ppre;
            last.next = null;

        }
    }

}

原始输出:19 -> 9 -> 5 -> 4 -> 17 -> 16 -> null

删除最后一个节点后:19 -> 9 -> 5 -> 4 -> 17 -> 16 -> null

1 个答案:

答案 0 :(得分:0)

这不是删除最后一个节点的方法,它是一种删除值等于数据的节点之后的所有节点的方法,除非它是一个节点长,在这种情况下它将全部删除。 (假设您有一个头部和最后一个节点,当然全局可用)

public void delete_at_end(int data) {
    Node ppre;
    if (head== null) {
        throw new RuntimeException("cannot delete");  // there is nothing to delete
    } else {
        if (head == last) { // if the head is the only node, delete it
            head = null;
            last = null;

         } else {
            ppre = head;  // otherwise we cycle through everything, checking if it is equal to the data we passed in
            while (ppre.next != null && ppre.data!=data) {
                ppre = ppre.next;
            }
            last=ppre;  // when we find the data we passed in, we set it equal to the last node
            last.next = null; // and terminate the rest of the list

        }
    }

}

如上面的评论所述,在null上调用.next会导致错误,所以如果你到达列表的末尾,并设置ppre = ppre.next(空值),那么设置last = ppre ,你将调用.next的空值。