Solved programming problem

Find Minimum Value from Linked List in C.

Source code

#include <stdio.h>

struct list

{

   int data;

   struct list *next;

};

typedef struct list node;

int min(node *head)

{

    node *start = head;

    int min_value = start->data; ///save the first value as min

    while(start->next != NULL)  ///find the min

    {

        if(start->data<min_value)

        {

            min_value =start->data;

            start = start->next;

        }

        else

        {

            start = start->next;

        }

    }

    return min_value;

}

int main()

{

    node *head,*new_node,*last,*start;

    int flag=0;

    start = NULL;

    do

    {

        printf("Press 1 to Enter a Value or 0 to Exit: ");

        scanf("%d",&flag);

        if(flag !=1)

        {

           break;

        }

        new_node = (node *)malloc(sizeof(node));

        printf("Please Enter Value: ");

        scanf("%d",&new_node->data);

        new_node->next= NULL; ///set the address as null;

        if(start==NULL)

        {

            start = new_node;

            head = new_node; ///this value is saved for safety

        }

        else

        {

          last=start;

           while(last->next!=NULL)

           {

               last= last->next; ///find the last index

           }

           last->next = new_node; ///save new value to last index

        }

    }while(flag==1);

     int MIN= min(start);

     printf("
The MinValue is: %d
",MIN);

    return 0;

}

Output

Press 1 to Enter a Value or 0 to Exit: 1
Please Enter Value: 13
Press 1 to Enter a Value or 0 to Exit: 1
Please Enter Value: 8
Press 1 to Enter a Value or 0 to Exit: 1
Please Enter Value: -10
Press 1 to Enter a Value or 0 to Exit: 0

The Min Value is: -10

Join the discussion

Add your comment