LinkedList的,错误的GET或添加

问题描述 投票:0回答:2

我创建一个链接列表,并有一些问题无论是在获取()或添加(索引数据)。我相信补充说明的是,虽然正确,所以我问你找到我做错了在get()方法。编辑:问题是我在索引0和索引1得到同样的价值。

public T get(int index) {
        int counter = 0;
        Node<T> temp = head;
        if(index < 0 || index > size() || head == null){
            throw new IndexOutOfBoundsException();
        } else {
            if(index == size()){
                temp = tail;
                return temp.data;
            }
            if(index == 0){
                return temp.data;
            }  else {
                while (counter +1 != index){
                    temp = temp.next;
                    counter++;
                }
                return temp.data;
            }
        }
    }
java data-structures
2个回答
0
投票

想象一下,你通过了指数== 1 - 你想要的第二个元素,是吗?

然而,while循环将永远不会进入(因为反== 0意味着计数器+ 1 ==指数)。因此,改变你的while循环“而(计数器<指数)”。

你会发现你并不需要明确:“如果(指数== 0)”,那么要么:)

事实上,这种循环再凝结成for循环,所以直:

for (int counter=0; counter < index; counter++) {
    temp = temp.next;
}

0
投票

您在while循环的条件是错误的。你需要去改变它TO-

while (counter != index){
   temp = temp.next;
   counter++;
}
© www.soinside.com 2019 - 2024. All rights reserved.