In: Computer Science
In C++, type a method getSmallest(), which returns the smallest number in the following linked list.
8->4->6->7->5 (8 is the head).
The required code and corresponding output are as follows. The main method is included to test the function getSmallest()
#include <iostream>
#include<malloc.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
// Function that returns smallest element
// from the linked list.
int getSmallest(struct Node* head)
{
// Declare a min variable and initialize
// it with head->data
int min = head->data;
// 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;
}
// Display linked list.
void printList(struct Node* head)
{
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
cout << "NULL" << endl;
}
// Driver program to test the function
int main()
{
// Start with empty list
struct Node* head = NULL;
// Using push() function to construct
// singly linked list
// Insertion at the begining
push(&head, 5);
push(&head, 7);
push(&head, 6);
push(&head, 4);
push(&head, 8);
cout << "Linked list is : " << endl;
// Call printList() function to display
// the linked list.
printList(head);
cout << "Smallest element in linked list:";
// Call getSmallest() function to get smallest
// element in linked list.
cout << getSmallest(head) << endl;
return 0;
}
Output: