Sum of smaller elements of nodes in a linked list in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a linked list with a node consisting of two values and a pointer. Our task is to create a program to find the sum of smaller elements of a node in a linked list.

Here, in the linked list we have two elements say X and Y. The program will find a minimum of x and y. The minimum elements from all nodes are added which is the required result.

Input

(5,2)->(7,9)->(6,3)->(36,24)->(19,26)->null

Output

55

Explanation

Let’s take the minimum of X and Y from each node −

node1 - mini = 5
node2 - mini = 7
node3 - mini = 3
node4 - mini = 24
node5 - mini = 19
Sum = 55

To solve this problem, we will use a straigth forward approach by visiting each node and find the minimum of X and Y. Then add it to the sum variable and then return sum, when node ends.

Algorithm

Initialize − sum = 0

Step1 − Traverse the list and do the following:

Step 1.1 − Find the minimum of head → X and head → Y.

Step 1.2 − add minimum to sum

Step 2 − Return Sum,

Example

Program to illustrate the working of our algorithm −

 Live Demo

#include <iostream>
using namespace std;
struct Node {
   int X;
   int Y;
   Node* next;
};
void addNode(Node** head, int x, int y){
   Node* ptr = *head;
   Node* temp = new Node();
   temp->X = x;
   temp->Y = y;
   temp->next = NULL;
   if (*head == NULL)
      *head = temp;
   else {
      while (ptr->next != NULL)
         ptr = ptr->next;
         ptr->next = temp;
   }
}
int findMinSum(Node* head){
   int sum = 0;
   while (head != NULL) {
      sum += min(head->X , head->Y);
      head = head->next;
   }
   return sum;
}
int main(){
   Node* head = NULL;
   addNode(&head, 5, 2);
   addNode(&head, 7, 9);
   addNode(&head, 6, 3);
   addNode(&head, 36, 24);
   addNode(&head, 19, 26);
   cout<<"The sum of smaller elements of nodes in Linked List is "<<findMinSum(head)<<endl;
   return 0;
}

Output

The sum of smaller elements of nodes in Linked List is 55
raja
Published on 05-Aug-2020 11:39:04
Advertisements