简体   繁体   中英

Removing a generic type node with the smallest value in a doubly linked list Java

This is the code I have for my getSmallest() method:

public T getSmallest() throws EmptyListException
{
    if(isEmpty())
        throw new EmptyListException("List is empty");


    DLNode<T> current = front;
    DLNode<T> minNode = current;
    int minimum = current.getValue();

    while(current.getNext() != null)
    {
        if(minimum > current.getValue())
        {
            minNode = current;
            minimum = current.getValue();
        }

        current = current.getNext();    
    }

    return current.getData();
}

Each node has a String called dataItem and an integer called value associated with it. I want to see which node has the smallest value and then return the dataItem. The problem is that I'm stuck in the while loop and don't know why. How would I properly traverse the list so that I don't get stuck in the while loop and can compare the minimum values?

As you've seen, you can't overload operators in Java, and > will only apply to numeric datatypes.

The generic solution for this is to have T extends Comparable<T> and use its compareTo method:

DLNode<T> current = front;
DLNode<T> minNode = current;
T minimum = current.getValue();

while (current.getNext() != null) {
    if (minimum.compareTo(current.getValue()) > 0) {
        minNode = current;
        minimum = current.getValue();
    }

    current = current.getNext();    
}

return current.getData();

(alternatively, if T isn't a Comparable , you could supply a custom Comparator and use it in a similar fashion).

The question is: why is the loop termination condition never reached?

As a doubly-linked list, does your list connect the last element to the first element? Will getNext() ever answer null?

Also, there are problems in the loop as written. See the corrected code, below. The problem of loop termination is probably not fixed by this update.

public T getSmallest() throws EmptyListException {
    if ( isEmpty() ) {
        throw new EmptyListException("List is empty");
    }

    DLNode<T> currentNode = front;

    int minValue = currentNode.getValue();
    DLNode<T> minNode = currentNode;

    while ( (currentNode = currentNode.getNext()) != null ) {
        int nextValue = currentNode.getValue();
        if ( nextValue < minValue ) {
            minNode = currentNode;
            minValue = nextValue;
        }
    }

    return minNode.getData();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM