Home » Program To Find The Maximum And Minimum Value Node From A Singly Linked List

Program To Find The Maximum And Minimum Value Node From A Singly Linked List

by Online Tutorials Library

Program to find the maximum and minimum value node from a singly linked list

Explanation

In this program, we need to find out the minimum and maximum value node in the given singly linked list.

Program to find the maximum and minimum value node from a singly linked list

We will maintain two variables min and max. Min will hold minimum value node, and max will hold maximum value node. In the above example, 1 will be minimum value node and 8 will be maximum value node. The algorithm to find the maximum and minimum node is given below.

Algorithm

  1. Create a class Node which has two attributes: data and next. Next is a pointer to the next node in the list.
  2. Create another class MinMax which has two attributes: head and tail.
  3. addNode() will add a new node to the list:
    1. Create a new node.
    2. It first checks, whether the head is equal to null which means the list is empty.
    3. If the list is empty, both head and tail will point to a newly added node.
    4. If the list is not empty, the new node will be added to end of the list such that tail’s next will point to a newly added node. This new node will become the new tail of the list.
  4. minNode() will display minimum value node:
    1. Define a variable min and initialize it with head’s data.
    2. Node current will point to head.
    3. Iterate through the list by comparing each node’s data with min.
    4. If min is greater than current’s data then, min will hold current’s data.
    5. At the end of the list, variable min will hold minimum value node.
    6. Display the min value.
  5. maxNode() will display maximum value node:
    1. Define a variable max and initialize it with head’s data.
    2. Node current will point to head.
    3. Iterate through the list by comparing each node’s data with max.
    4. If max is less than current’s data then, max will hold current’s data.
    5. At the end of the list, variable max will hold maximum value node.
    6. Display the max value.

Solution

Python

Output:

 Minimum value node in the list: 1  Maximum value node in the list: 8  

C

Output:

Minimum value node in the list: 1  Maximum value node in the list: 8  

JAVA

Output:

Minimum value node in the list: 1  Maximum value node in the list: 8  

C#

Output:

Minimum value node in the list: 1  Maximum value node in the list: 8  

PHP

Output:

 Minimum value node in the list: 1  Maximum value node in the list: 8  

Next Topic#

You may also like