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

查看:41
本文介绍了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天全站免登陆