在 C++ 中查詢連結串列的長度(迭代和遞迴)


我們將在此介紹如何使用迭代和遞迴方法查詢連結串列的長度。如果給出了頭指標,我們必須按照以下步驟來獲取長度。

  • 對於迭代方法 -

    • 獲取連結串列的頭,直到當前指標不為空,轉到下一個節點並增加計數。

  • 對於遞迴方法 -

    • 將頭作為引數傳遞,基本條件是當引數為空時,返回 0,否則遞迴進入連結串列並從當前節點發送下一個節點,返回 1 + 子連結串列的長度。

示例

 線上演示

#include<iostream>
using namespace std;
class Node {
   public:
      int data;
   Node* next;
};
void append(struct Node** start, int data) {
   struct Node* new_node = new Node;
   new_node->data = data;
   new_node->next = (*start);
   (*start) = new_node;
}
int count_recursive(Node* start) {
   if (start == NULL)
      return 0;
   return 1 + count_recursive(start->next);
}
int count_iterative(Node* start) {
   int count = 0;
   Node* current = start;
   while (current != NULL) {
      count++;
      current = current->next;
   }
   return count;
}
int main() {
   Node* start = NULL;
   append(&start, 1);
   append(&start, 3);
   append(&start, 1);
   append(&start, 2);
   append(&start, 1);
   cout << "Node count using iterative approach: " << count_iterative(start) << endl;
   cout << "Node count using recursion: " << count_recursive(start);
}

輸出

Node count using iterative approach: 5
Node count using recursion: 5

更新於:2019-12-19

626 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始吧
廣告