C++实现循环链表节点求和
在这个问题中,我们给定一个循环链表。我们的任务是创建一个程序来查找循环链表节点的和。
我们只需要将链表的所有节点值相加即可。
一些重要的定义
链表是由链接连接在一起的数据结构序列。
循环链表是链表的一种变体,其中第一个元素指向最后一个元素,最后一个元素指向第一个元素。单链表和双链表都可以构成循环链表。
现在,让我们来看一个例子来理解这个问题:
输入
14 -> 1 -> 7 -> 9 -> 2 -> 6
输出
39
解释
sum = 14 + 1 + 7 + 9 + 2 + 6 = 39
为了解决这个问题,我们将遍历链表。并将每个节点的值添加到一个sum变量中。遍历整个列表后,返回sum。
算法
步骤 1 - 初始化 sum = 0 和 sumPointer =
步骤 2 - 当 sumPointer != head 时执行循环
步骤 2.1 - 将当前节点的值添加到 sum 中,即 sum += sumPointer → value。
步骤 2.2 - 将指针递增到下一个节点,即 sumPointer = sumPointer → next。
步骤 3 - 返回 Sum。
示例
演示解决方案的程序:
#include <iostream> using namespace std; struct Node { int data; struct Node* next; }; void pushNode(struct Node** head_ref, int data) { struct Node* ptr1 = (struct Node*)malloc(sizeof(struct Node)); struct Node* temp = *head_ref; ptr1->data = data; ptr1->next = *head_ref; if (*head_ref != NULL) { while (temp->next != *head_ref) temp = temp->next; temp->next = ptr1; } else ptr1->next = ptr1; *head_ref = ptr1; } int CalcSumCirList(struct Node* head) { struct Node* sumPointer = head; int sum = 0; if (head != NULL) { do { sumPointer = sumPointer->next; sum += sumPointer->data; } while (sumPointer != head); } return sum; } int main(){ struct Node* head = NULL; pushNode(&head, 4); pushNode(&head, 7); pushNode(&head, 12); pushNode(&head, 1); pushNode(&head, 9); pushNode(&head, 6); cout<<"The sum of Circular linked list is "<<CalcSumCirList(head); 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 Circular linked list is 39
广告