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

輸出

The sum of Circular linked list is 39

更新於:2020年8月6日

243 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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