C program to find maximum or greatest keynode in a linked list
PROGRAM:
#include <stdio.h>#include <stdlib.h>
//Creating structure
struct node
{
int data;
struct node *link;
}*first=NULL;
struct node * create(struct node *);
struct node * maxNode(struct node *);
//main function
int main()
{
struct node *max=NULL;
printf("\nEnter elements to create linked list\n");
first=create(first);
printf("\nLinked list created!\n");
max=maxNode(first);
printf("\nMaximum/Greatest key node in linked list is %d\n",max->data);
return 0;
}
//function to create linked list
struct node * create(struct node *first)
{
struct node *new_node;
int choice=0;
do
{
new_node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter an element\n");
scanf("%d",&new_node->data);
new_node->link=NULL;
if(first==NULL)
first=new_node;
else
{
new_node->link=first;
first=new_node;
}
printf("\nEnter 1 to continue, 0 to stop\n");
scanf("%d",&choice);
}while(choice==1);
return first;
}
//function to find maximum/greatest key node in the linked list
struct node * maxNode(struct node * first)
{
struct node *temp=NULL, *max=NULL;
if(first==NULL)
{
printf("\nLinked list does not exist\n");
return first;
}
else if(first->link==NULL)
return first;
else
{
max=first;
temp=first->link;
while(temp!=NULL)
{
if(max->data<temp->data)
{
max=temp;
temp=temp->link;
}
else
{
temp=temp->link;
}
}
return max;
}
}
OUTPUT:
TRIAL 1:
Enter elements to create linked listEnter an element
10
Enter 1 to continue, 0 to stop
1
Enter an element
5
Enter 1 to continue, 0 to stop
1
Enter an element
50
Enter 1 to continue, 0 to stop
1
Enter an element
20
Enter 1 to continue, 0 to stop
1
Enter an element
15
Enter 1 to continue, 0 to stop
1
Enter an element
32
Enter 1 to continue, 0 to stop
0
Linked list created!
Maximum/Greatest key node in linked list is 50
TRIAL 2:
Enter elements to create linked listEnter an element
100
Enter 1 to continue, 0 to stop
0
Linked list created!
Maximum/Greatest key node in linked list is 100