having trouble figuring this out, every time i run my code the program goes on forever, everything else in the linked list works perfectly well. including the delete.
public Node smallestValue() {
Node current = firstL;
int min = current.data;
if (!isEmpty()) {
while (current != null) {
if (min < current.data) {
min = current.data;
current = current.next;
}
}
} else {
System.out.println("empty list");
}
System.out.println();
System.out.println(min);
return current;
}
You need to advance current
whether or not min < current.data
. Just move the assignment to outside the if
. (Also, as @0x499602D2 points out in a comment, to find the smallest value you need to change min
when it is greater than current.data
.)
while(current != null){
if(min > current.data){
min = current.data;
}
current = current.next;
}
It might be cleaner to do this as a for
loop:
for (Node current = firstL, int min = current.data;
current != null;
current = current.next)
{
min = Math.min(min, current.data);
}
Because this is inside the test for an empty list, this has the advantage of not crashing if firstL
is null
(which, I assume, cannot happen if the list is not empty).
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.