In: Computer Science
Question 1:
Write a method getSmallest(), which returns the smallest number in the linked list.
Question 2:
Write a member method getPosition(int entry) which returns the position of the entry is in the linked list. If the entry is not in the list, return -1.
Please use C++ language for both questions, I only need functions.
Question 1:
Function getSmallest() that returns smallest element can be defined as follows:
// 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;
}
Question 2:
Function getPosition(int entry) that returns position of a particular element can be defined as follows:
//Checks whether the value entry is present in linked list
int getPosition(struct Node* head, int entry)
{
int pos=1; //Initialize node count
while (head != NULL)
{
if (head->data == entry)
return pos; //data found
head = head->next;
pos++;
}
return -1; //data not found
}