简体   繁体   中英

get minimum element from linked list java

I am trying to get the minimum element from a linked list. However my currnet code doesnt traverse through all the elements, it only checks the first pair of elements. I know where my error is, just don't know why its not traversing even though I have used next.

    public class ListOfNVersion03PartB
{   
    private int thisNumber;              // the number stored in this node
    private ListOfNVersion03PartB next;  // forms a linked list of objects

    private final int nodeID;            // a unique ID for each object in the list

    private static int nodeCount = 0;    // the number of list objects that have been created


    public ListOfNVersion03PartB(int num)
    {
        thisNumber = num;
        next = null;

        ++nodeCount;
        nodeID = nodeCount;

    } 

public ListOfNVersion03PartB(int [] num)
{
    this(num[0]);  // in this context, "this" invokes the other constructor

    for (int i=1 ; i<num.length ; ++i)
        insertLast(num[i]);

} 

        public int minVal()
    {

        if(next.thisNumber> thisNumber)
        return thisNumber;

        else
         return next.minVal();   

    }

Because you didn't assign next to another node and its value is null , So when you call minVal() will throw NullPointerException

You can check if next is null or not, like this

        public int minVal() {
            ListOfNVersion03PartB current = this;
            int min = Integer.MAX_VALUE;
            while (current != null) {
                if (current.thisNumber < min)
                    min = current.thisNumber;
                current = current.next;
            }
            return min;
        }

in your minVal() method, it returns at very first line because of linked list you provided.

if(next.thisNumber> thisNumber)    // 8 > 4
        return thisNumber;         // returns 4

You must iterate through all elements and find mininum. Please do something like this:

public int minVal()
    int min = thisNumber;
    ListOfNVersion03PartB temp = next;   // set temp to next element initially
    while(temp.next ! null) {
       if (temp.thisNumber < min) {
           min = temp.thisNumber;
       }
       temp = temp.next;
    }
    return min;
}

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