For a given linked list, you are supposed to write two separate functions that finds the largest and the smallest number in a linked list and print both the numbers.
Example 1:
Input: 4 6 2 8 1
Output: Largest Number: 8
Output: Smallest Number: 1
Example 2:
Input: 4 5 9 8 2
Output: Largest Number: 9
Output: Smallest Number: 2
Steps to find Largest number:
Initialise an integer variable
max
toINT_MIN
.Using temporary pointer
temp
start traversing the linked list and compare each data element in the linked list with the variablemax
until the end of linked list.If the current node’s data is greater than value of
max
, then store the value of the current node’s data intomax
.Finally, print the value of variable
max
which contains the largest number of the linked list.
Steps to find Smallest number:
Initialise an integer variable
min
toINT_MAX
.Using temporary pointer
temp
start traversing the linked list and compare each data element in the linked list with the variablemin
until the end of linked list.If the current node’s data is lesser than the value of
min
, then store the value of the current node’s data intomin
.Finally, print the value of variable
min
which contains the smallest number of the linked list.
Note : We are using INT_MAX because all the data elements are lesser than this and INT_MIN because all the data elements are greater than this. Using these two macros our findings become very easy.
C program that finds the largest and the smallest number in the linked list.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct node
{
int data;
struct node * next;
};
void displayLL(struct node * head)
{
struct node * temp;
temp = head;
temp=head;
while(temp!=0)
{
printf("%d ",temp->data);
temp = temp->next;
}
}
void small(struct node *head)
{
struct node *temp = head;
int min;
min = INT_MAX;
while(temp != NULL)
{
if(min > temp->data)
{
min = temp->data;
}
temp = temp->next;
}
printf("\n--------------------------------\n");
printf("Smallest number of linked list : %d", min);
}
void large(struct node *head)
{
struct node *temp = head;
int max;
max = INT_MIN;
while(temp != NULL)
{
if(max < temp->data)
{
max = temp->data;
}
temp = temp->next;
}
printf("\n--------------------------------\n");
printf("Largest number of linked list : %d", max);
}
int main()
{
struct node *head = 0, *newnode, *temp;
int n, choice, newdata;
// Create Linked List //
printf("Enter the number of nodes in the list : ");
scanf("%d", &n);
if(n == 0)
{
printf("--------------------------------\n");
printf("Linked list cannot be empty");
exit(0);
}
for(int i = 1; i<=n; i++)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("Enter the data%d : ", i);
scanf("%d", &newnode->data);
newnode->next = 0;
if(head == 0)
{
head = temp = newnode;
}
else
{
temp->next = newnode;
temp = newnode;
}
}
printf("--------------------------------\n");
printf("Linked list : ");
displayLL(head);
small(head);
large(head);
}
Top comments (0)