In: Computer Science
Evaluate and write an algorithm to find the largest item in an unsorted singly linked list with cells containing integers
If You have Any Query Regarding this please ask in comment section I will be there to solve all your query in comment section immediately hope you will like it
So below is implementation of question so I have used the idea to traverse the whole linklist till when start is not pointing to null initialise the max variable with INT_MAX After that check a condition that if max value is less then head value then head value is assign to max otherwise head point to next node. Continue this process until start is not equal to NULL.
// C++ Program to find largest
// elements in unsorted singly linked list.
#include <bits/stdc++.h>
using namespace std;
/* Linked list node */
struct Node {
int data;
struct Node* next;
};
int largestElement(struct Node* start)
{
int max = INT_MIN;
while (start != NULL) {
if (max < start->data) //if max vakue will hight we store in the varibale
max = start->data;
start = start->next;
}
return max;
}
// Function that insert_ele the element in linked list.
void insert_ele(struct Node** start, int data)
{
// Allocate dynamic memory for newNode.
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
// Assign the data into newNode.
newNode->data = data;
// newNode->next assign the address of
// start node.
newNode->next = (*start);
// newNode become the headNode.
(*start) = newNode;
}
// Display linked list.
void display(struct Node* start)
{
while (start != NULL) {
printf("%d -> ", start->data);
start = start->next;
}
cout << "NULL" << endl;
}
// Driver program to test the functions
int main()
{
// Start with empty list
struct Node* start = NULL;
// Using insert_ele() function to construct
insert_ele(&start, 56);
insert_ele(&start, 11);
insert_ele(&start, 15);
insert_ele(&start, 7);
insert_ele(&start, 22);
cout << "Linked list is : " << endl;
display(start);
cout << "Maximum element in linked list:";
cout << largestElement(start) << endl; // return largest element in unsorted linklist
return 0;
}