Solved programming problem

Find Maximum value from Linked List in C.

Source code

#include <stdio.h>

struct list

{

   int data;

   struct list *next;

};

typedef struct list node;

int max(node *head)

{

    node *start = head;

    int max_value = start->data; ///save the first value as max

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

    {

        if(start->data>max_value)

        {

            max_value =start->data;

            start = start->next;

        }

        else

        {

            start = start->next;

        }

    }

    return max_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 S 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 MAX= max(start);

     printf("
The Max Value is: %d
",MAX);

    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 Max Value is: 13

Join the discussion

Add your comment