LinkedList remove at index java

人走茶凉 提交于 2021-02-05 09:48:41

问题


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 with the debugger in eclipse but couldn't catch the problem.

Each Node contains a token. I have included the Token class, Node class. I have written my methods in the List class and included a Test class.

The remove method is currently removing the node next to the specified index. How can I get this to work? My apologies for the long post.

public class thelist{

    public Node head;

    public List() {
        head = null;
    }

    public Node remove(int index) {
        Node node= head;
        for (int i = 0; i < index; i++) {
            node= node.next;
        }
        node.next = node.next.next;
        return node;
    }

回答1:


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


来源:https://stackoverflow.com/questions/36577328/linkedlist-remove-at-index-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!