【问题标题】:LinkedList remove at index javaLinkedList 在索引 java 处删除
【发布时间】:2016-04-12 15:11:20
【问题描述】:

我从头开始创建了一个 remove 方法,它从指定索引处的链表中删除一个节点。

它没有删除正确的节点。我尝试在 Eclipse 中使用调试器,但无法解决问题。

每个节点都包含一个令牌。 我已经包含了 Token 类,Node 类。 我在 List 类中编写了我的方法并包含了一个 Test 类。

remove 方法当前正在删除指定索引旁边的节点。 我怎样才能让它工作?对于这篇长篇文章,我深表歉意。

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

【问题讨论】:

  • ref.next = ref.next.next; 应该是ref.previous.next = ref.next;

标签: java linked-list


【解决方案1】:

问题在于,一旦找到正确的索引,您将删除 NEXT 节点,而不是索引处的节点。找到正确的节点后,可以将ref.previous.next 设置为ref.next;因此,删除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();
}

【讨论】:

  • index0 时会报错。假设head.previousnull
  • 如果您尝试删除最后一个索引(ref.next 为空)或第一个索引(ref.previous 也为空),这将获得 NPE,因此您需要检查并处理这些相应的情况。
  • 是的,index0 会抛出 NullPointerException,我已经更正了。但是,如果它是最后一个索引,它不会引发期望,因为 ref.next 只会引用 null,而不是尝试访问 null 的属性。
  • 谢谢,我明白了
  • 在您的add 方法中,当您将tail.next 设置为新节点后,将tail.next.previous 设置为tail,然后将tail 设置为tail.next。本质上,当你添加一个新节点时,你需要添加对前一个节点的引用。
【解决方案2】:
   public void Atposition(E pos){
    Node<E> curr = head, prev = null;
    if(curr!=null&&curr.getElement()==pos){
    curr=head;
    head=head.getNext();
    size--;
    return;
}while(curr!=null&&curr.getElement()!=pos){
    prev = curr;
    curr=curr.getNext();
}
if(curr==null){
    System.out.print("the list is empty");
    return;
}
    prev.next=curr.next;
}

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 2014-09-22
    相关资源
    最近更新 更多