linkedlist,get或add中的bug

lmyy7pcs  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(278)

我正在创建一个链表,在get()或add(index,data)中遇到了一些问题。我相信add是正确的,所以我要求您找出get()方法中的错误。edit:问题是索引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;
            }
        }
    }
liwlm1x9

liwlm1x91#

while循环中的条件是错误的。你需要把它改成-

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

c3frrgcw2#

假设您传入了index==1—您想要第二个元素,是吗?
但是,while循环永远不会进入(因为counter==0意味着counter+1==index)。所以将while循环改为“while(counter<index)”。
您将发现不需要显式的“if(index==0)”,然后:
实际上,这个循环会压缩成一个直for循环,所以:

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

相关问题