Basically I don't know why my integer n
doesn't get higher.
Thanks for every answer!
public int n;
public int firstIndexOf(T val) {
if (val == this.getValue()) {
return n;
} else {
if (val != this.getValue() && this.next != null) {
n++;
return this.next.firstIndexOf(val);
} else {
return -1;
}
}
}
The increment (n++) was in the wrong condition check:
private int n = 0;
public int firstIndexOf(int val) {
if ( val == this.getValue() ) {
return n+1; //This is were the increment should happen
}
else {
if ( this.next != null ) {
return this.next.firstIndexOf(val);
} else {
return -1;
}
}
}
Also if you want to count all the elements in your linked list which have the same value as val, you can use this:
private int n = 0;
public int firstIndexOf(int val) {
if ( val == this.getValue() ) {
if ( this.next != null ) {
return 1 + this.next.firstIndexOf(val);
}
else {
return 1;
}
} else {
if ( this.next != null ) {
return this.next.firstIndexOf(val);
} else {
return 0;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.