LinkedList remove at index java

后端 未结 1 509
傲寒
傲寒 2021-01-28 13:47

I\'ve made a remove method from scratch that removes a Node from a linked list at a specified index.

It\'s not removing the correct Node. I\'ve tried to step through wit

1条回答
  •  猫巷女王i
    2021-01-28 14:30

    The problem is that once you get to the correct index, you're removing the NEXT node, not the one at the index. Once you find the correct node, you can to set ref.previous.next to ref.next; thus, cutting out ref.

    public Token remove(int index) {
        if (index<0 || index >=size()) {
            throw new IndexOutOfBoundsException();
        }
        Node ref = head;
        for (int i = 0; i < index; i++) {
            ref = ref.next;
        }
        if (index == 0) {
            head = ref.next;
        } else {
            ref.previous.next = ref.next;
        }
        size--;
        return ref.getObject();
    }
    

    0 讨论(0)
提交回复
热议问题