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;
}

輸出

The sum of smaller elements of nodes in Linked List is 55

更新於: 2020年8月5日

81 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.