# 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;
};
Node* temp = new Node();
temp->X = x;
temp->Y = y;
temp->next = NULL;
else {
while (ptr->next != NULL)
ptr = ptr->next;
ptr->next = temp;
}
}
int sum = 0;
}
return sum;
}
int main(){
}
The sum of smaller elements of nodes in Linked List is 55