C++链表中节点较小元素的和
在这个问题中,我们得到一个链表,其中节点包含两个值和一个指针。我们的任务是创建一个程序来查找链表中节点较小元素的和。
在这里,在链表中我们有两个元素,例如 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
为了解决这个问题,我们将采用一种直接的方法,访问每个节点并找到 X 和 Y 的最小值。然后将其添加到 sum 变量中,当节点结束时返回 sum。
算法
初始化 − sum = 0
步骤1 − 遍历列表并执行以下操作
步骤 1.1 − 查找 head → X 和 head → Y 的最小值。
步骤 1.2 − 将最小值添加到 sum
步骤2 − 返回 Sum
示例
程序说明我们算法的工作原理 −
#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; }
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
The sum of smaller elements of nodes in Linked List is 55
广告