使用 java 编写两个方法 min 和 max 来查找链表中的最大值和最小值,但输入列表是整数数组

Using java write two methods min and max to find maximum value and minimum value in linked list but the input list is array of integers

您为 minNode() 函数输入大于号,为 maxNode() 输入小于号。

public void minNode() {  
    Node current = head;  
    int min;  

    if(head == null) {  
        System.out.println("List is empty");  
    }  
    else {  
        //Initializing min with head node data  
        min = head.data;  

        while(current != null){  
             //If current node's data is smaller than min  
             //Then, replace value of min with current node's data  


            // Your error was here:

             min = Math.min(min, current.data); // You can simplify updating min to this.




             current= current.next;  
        }  
        System.out.println("Minimum value node in the list: "+ min);  
    }  
}  

maxNode()变成这样:

public void maxNode() {  
    Node current = head;  
    int max;  

    if(head == null) {  
        System.out.println("List is empty");  
    }  
    else {  
        //Initializing max with head node data  
        max = head.data;  

        while(current != null){  
             //If current node's data is greater than max  
             //Then, replace value of max with current node's data  


             // Your error was here:

             max = Math.max(max, current.data); // And updating max becomes this.




             current = current.next;  
        }  
        System.out.println("Maximum value node in the list: "+ max);  
    }  
}  

您提供的代码正在以正确的方式执行。

你也可以用

MaximumMinimum sList = new MaximumMinimum(); 
List<Integer> list = new ArrayList<>();
Node head = sList.head;
while(head != null){
    list.add(head.data);
    head= head.next;
}
//no recommended if you want to design your own method    
System.out.println(list);
System.out.println(Collections.max(list));
System.out.println(Collections.min(list));

用于输入整数数组到

public void stores(int[] array)
{
    for(int element:array)
    {
        this.addNode(element);
    }
}

那么如果你在 main

中 运行
 int[] elements = {1, 78, -9, 42 , 0, 14};
    sList.stores(elements);
    sList.maxNode(); //78
    sList.minNode();//-9

如果您想以 java 8 种方式进行,也可以使用 Arrays.stream(array_name).forEach(e->sList.add(e))