在这个问题中,我们得到了一个链表,链表的节点由两个值和一个指针组成。我们的任务是创建一个程序,以查找链表中节点的较小元素的总和。
在此,在链接列表中,我们有两个元素,分别是X和Y。程序将找到x和y的最小值。添加了来自所有节点的最小元素,这是必需的结果。
输入-
(5,2)->(7,9)->(6,3)->(36,24)->(19,26)->null
输出-
55
说明-
让我们从每个节点取X和Y的最小值-
node1 - mini = 5 node2 - mini = 7 node3 - mini = 3 node4 - mini = 24 node5 - mini = 19 Sum = 55
为了解决这个问题,我们将使用straigth正演方法,通过访问每个节点并找到X和Y的最小值。然后将其添加到sum变量中,然后在节点结束时返回sum。
初始化-sum = 0
步骤1-遍历列表并执行以下操作:
步骤1.1-找到head→X和head→Y的最小值。
步骤1.2-将最小值加和
步骤2-返回总和,
用来说明我们算法工作原理的程序-
#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;
}输出结果
The sum of smaller elements of nodes in Linked List is 55