LinkedList 在索引处删除 java [英] LinkedList remove at index java

查看:28
本文介绍了LinkedList 在索引处删除 java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

它没有删除正确的节点.我已经尝试在 Eclipse 中使用调试器单步调试,但未能发现问题.

It's not removing the correct Node. I've tried to step through with the debugger in eclipse but couldn't catch the problem.

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

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.

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

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

推荐答案

问题在于,一旦获得正确的索引,就会删除 NEXT 节点,而不是索引中的节点.一旦找到正确的节点,就可以将ref.previous.next 设置为ref.next;因此,删除ref.

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

这篇关于LinkedList 在索引处删除 java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆