C++ 中連結串列的交替節點之和


在這個問題中,我們給定一個連結串列。我們的任務是列印連結串列的交替節點的總和。

連結串列 是一種資料結構序列,它們透過連結連線在一起。

現在,讓我們回到這個問題。在這裡,我們將新增連結串列的交替節點。這意味著我們將新增位置為 0、2、4、6、… 的節點。

讓我們舉個例子來理解這個問題,

輸入

4 → 12 → 10 → 76 → 9 → 26 → 1

輸出

24

解釋

considering alternate strings −
4 + 10 + 9 + 1 = 24

為了解決這個問題,我們將逐個訪問每個節點,並針對每個下一個節點。我們將值新增到總和中。為了檢查節點,我們將使用一個標誌。

這可以透過迭代或遞迴來完成。我們將在本文中討論這兩種方法,

示例

迭代方法

即時演示

#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void pushNode(struct Node** head_ref, int newData) {
   struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
   newNode->data = newData;
   newNode->next = (*head_ref);
   (*head_ref) = newNode;
}
int sumAlternateNodeIt(struct Node* head) {
   bool flag = true;
   int sum = 0;
   while (head != NULL){
      if (flag)
         sum += head->data;
      flag = !flag;
      head = head->next;
   }
   return sum;
}
int main(){
   struct Node* head = NULL;
   pushNode(&head, 54);
   pushNode(&head, 12);
   pushNode(&head, 87);
   pushNode(&head, 1);
   pushNode(&head, 99);
   pushNode(&head, 11);
   cout<<"The sum of alternate nodes is "<<sumAlternateNodeIt(head);
   return 0;
}

輸出

The sum of alternate nodes is 24

示例

遞迴方法

即時演示

#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void pushNode(struct Node** head_ref, int new_data){
   struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
void sumAlternateNodeRec(struct Node* node, int& sum, bool flag = true){
   if (node == NULL)
      return;
   if (flag == true)
   sum += (node->data);
   sumAlternateNodeRec(node->next, sum, !flag);
}
int main(){
   struct Node* head = NULL;
   pushNode(&head, 54);
   pushNode(&head, 12);
   pushNode(&head, 87);
   pushNode(&head, 1);
   pushNode(&head, 99);
   pushNode(&head, 11);
   int sum = 0;
   sumAlternateNodeRec(head, sum, true);
   cout<<"The sum of alternate nodes is "<<sum;
   return 0;
}

輸出

The sum of alternate nodes is 24

更新於:2020-08-06

485 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.