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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP