C program to find minimum/least key node in 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 * minNode(struct node *);
//main function
int main()
{
struct node *min=NULL;
printf("\nEnter elements to create linked list\n");
first=create(first);
printf("\nLinked list created!\n");
min=minNode(first);
printf("\nMinimum/Least key node in linked list is %d\n",min->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 minimum/least key node in the linked list
struct node * minNode(struct node * first)
{
struct node *temp=NULL, *min=NULL;
if(first==NULL)
{
printf("\nLinked list does not exist\n");
return first;
}
else if(first->link==NULL)
return first;
else
{
min=first;
temp=first->link;
while(temp!=NULL)
{
if(min->data>temp->data)
{
min=temp;
temp=temp->link;
}
else
{
temp=temp->link;
}
}
return min;
}
}
OUTPUT:
TRIAL 1:
Enter elements to create linked listEnter an element
10
Enter 1 to continue, 0 to stop
1
Enter an element
58
Enter 1 to continue, 0 to stop
1
Enter an element
5
Enter 1 to continue, 0 to stop
1
Enter an element
32
Enter 1 to continue, 0 to stop
1
Enter an element
46
Enter 1 to continue, 0 to stop
0
Linked list created!
Minimum/Least key node in linked list is 5
TRIAL 2:
Enter elements to create linked listEnter an element
25
Enter 1 to continue, 0 to stop
0
Linked list created!
Minimum/Least key node in linked list is 25