2

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;
}
2
  • 3
    move current = current.next out of the if statement Commented Nov 28, 2017 at 4:19
  • 1
    And your condition is wrong. It should be if (min > current.data). Commented Nov 28, 2017 at 4:19

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.