In: Computer Science
#include <iostream>
using namespace std;
//linked list node
struct Node {
int data;
struct Node* next;
};
// function that returns smallest element from linked list
int minimumElement(struct Node* head)
{
//declare min as largest value
int min = 9999999;
// Check loop while head not equal to NULL
while (head != NULL) {
// If min is greater then head->data then assign value of head->data to min otherwise node point to next node.
if (min > head->data)
min = head->data;
head = head->next;
}
return min;
}
// Function that push the element in linked list.
void push(struct Node** head, 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 head node
newNode->next = (*head);
// newNode become the headNode.
(*head) = newNode;
}
//main function
int main()
{
//initially empty list
struct Node* head = NULL;
//using push() function to construct singly linked list 10->22->18->14->15
push(&head, 15);
push(&head, 14);
push(&head, 18);
push(&head, 22);
push(&head, 10);
cout << "Minimum element in linked list: ";
//call smallestElement() function to get minimum element from linked list
cout << minimumElement(head) << endl;
return 0;
}
Please refer below screenshot of code for better understanding of code indentation.
Above image is shown main function with output of code.