自定义LinkedList:remove方法无法按预期工作

时间:2014-11-10 20:19:42

标签: java data-structures linked-list

我正在实现自定义remove()类的LinkedList方法,但它不会从列表中删除任何项目,我无法弄清楚原因。

我是这样做的:

public void remove(int position) {
        if (position < 0 || position >= size) {
            throw new IndexOutOfBoundsException(
                    "position should be beween 0 and size - 1");
        }

        Cell current = top;
        for (int i = 0; i < position; i++) {
            current = current.next;
        }
        current = current.next.next;
        size--;
}

此方法尝试删除2个节点之间的项目(删除第一个节点和忽略最后一个节点的情况)。

这是我正在执行的测试用例,在尝试删除索引为2的元素后,它仍会打印孔列表:

CustomList<String> list = new CustomList<String>();
list.add("Hello");
list.add("morena");
list.add("What");
list.add("Miranda");
list.add("Aston");      

list.remove(2);

list.printAll();

完成后,这里是列表的完整实现:​​

public class CustomList<T> {

    private class Cell {
        T data;
        Cell next;

        public Cell(T data) {
            this.data = data;
        }
    }

    private Cell top;
    private int size;

    public void add(T data) {
        addAtEndInOn(data);
        size++; 
    }

    /**
     * adds an item at the end of the list in O(n) by iterating the whole list
     * before adding the node
     */
    private void addAtEndInOn(T data) {
        if (top == null) {
            top = new Cell(data);
        } else {
            Cell current = top;
            while (current.next != null) {
                current = current.next;
            }
            current.next = new Cell(data);
        }
    }

    public void remove(int position) {
        if (position < 0 || position >= size) {
            throw new IllegalArgumentException(
                    "position should be a positive number");
        }

        Cell current = top;
        for (int i = 0; i < position; i++) {
            current = current.next;
        }
        current = current.next.next;
        size--;
    }

    public void printAll() {
        Cell current = top;
        while (current != null) {
            System.out.println(current.data);
            current = current.next;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

current = current.next.next不会在列表中进行任何更改。

要删除元素,您需要写:

current.next = current.next.next;

这将删除当前元素旁边的元素。它不是你要删除的元素,你应该更改for循环,以便当current是要删除的元素之前的元素时它停止。

确保测试current.next不为空,以避免NullPointerException

答案 1 :(得分:2)

You have to break the link, not just change the position of current

你必须打破链接,而不仅仅是改变当前的位置。该链接由current.next

表示