链接列表,获取或添加中的错误



我正在创建一个链表,但在get((或add(index,data(中遇到了一些问题。我确实相信添加是正确的,所以我请你找到我在 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;
            }
        }
    }

想象一下你在 index==1 中传递 - 你想要第二个元素,是吗?

但是,您的 while 循环永远不会进入(因为计数器 ==0 表示计数器 +1 == 索引(。因此,请将您的 while 循环更改为"while(计数器<索引("。>

你会发现你不需要明确的"if(index==0(",那么要么:)

事实上,这个循环然后压缩成一个直的 for 循环,所以:

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

while 循环中的条件是错误的。您需要将其更改为-

while (counter != index){
   temp = temp.next;
   counter++;
}

最新更新