In: Computer Science
#include <stdio.h>
typedef struct node {
int value;
struct node *next;
} node;
int printMax(node *first) {
int max=first->value;
while(first!=NULL){
if(max<first->value)
max=first->value;
first=first->next;
}
return max;
}
int main(void) {
node nodes[5]; //enough to run our tests
int i,array[5] = {3,5,1,10,9};
for(i=0; i < sizeof(nodes)/sizeof(node)-1; i++)
{
nodes[i].next =
&nodes[i+1];
nodes[i].value = array[i];
}
nodes[i].value = array[4];
nodes[i].next = NULL;
printf("The maximum number is %d\n",
printMax(&nodes[0]));
return 0;
}
Explanation:
1)take a variable max which tracks the max value in the
array,
2)this max was intially loaded with the first node value,to compare
with the remaining elements of the array.
3)here we are using while loop to traverse through each node.
4)for traversing purpose we use first pointer itself.
5)in the loop compare each value in the each node with max variable
if it is more than max than max will replace with that value.
6)after each iteration fitst pointer move foreword towords
end.
7) when first pointer points NULL it will stop.