In this article we are going to see how we can find the max and min values in a linked list by using Java programming language.
Java Program to Find the Max and Min Values in a Linked List
Approach:
- Create a linked list.
- Add elements to the list.
- Display the elements.
- Call the user defined method
minVal()
andmaxVal()
method to find the min and max value from the list. The method stores the head element in variable and compares it with the data from the rest of the list and prints the min/max value.
Program:
import java.util.*; // Main class public class Main { // Class Node that defines the two linked list variables class Node { int data; Node nextNode; // constructor to create a node public Node(int data) { this.data = data; this.nextNode = null; } } // Setting the head and end of the node as NULL public Node head = null; public Node tail = null; // method to find the minimum value in the linked list public void minVal() { Node curr = head; int min; if(head == null) { System.out.println("Linked list is empty"); } else { //Store the first node data min = head.data; while(curr != null) { //compare min with each node and if any value is smaller than min replace min with it. if(min > curr.data) { min = curr.data; } curr= curr.nextNode; } System.out.println("Minimum value in the list is "+ min); } } // method to find the maximum value in the linked list public void maxVal() { Node curr = head; int max; if(head == null) { System.out.println("Linked list is empty"); } else { //Storing the first node data in max max = head.data; while(curr != null) { //compare max with each node and if any value is bigger than max replace min with it. if(max < curr.data) { max = curr.data; } curr = curr.nextNode; } System.out.println("Maximum value in the list is "+ max); } } // method to add a node to the end of the linked list public void add(int data) { Node newNode = new Node(data); // Checks if there was any previous node if(head==null) { head = newNode; tail = newNode; } else { tail.nextNode = newNode; tail = newNode; } } // Method to display all the nodes of the linked list public void show() { Node curr = head; // If the head is pointing to no node then the linked list is empty if(head==null) System.out.println("Linked List is empty"); else { System.out.println("The nodes are:"); while(curr!=null) { System.out.print(curr.data+","); curr = curr.nextNode; } System.out.println(); } } public static void main(String[] args) { // create an object of the main class Main ll = new Main(); // add elements to the linked list ll.add(10); ll.add(20); ll.add(30); ll.add(40); ll.add(50); // display the nodes ll.show(); ll.minVal(); ll.maxVal(); } }
Output: The nodes are: 10,20,30,40,50, Minimum value in the list is 10 Maximum value in the list is 50
Grab the opportunity to learn all effective java programming language concepts from basic toadvance levels by practicing these Java Program Examples with Output.