在 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 次浏览

开启你的 职业生涯

完成课程并获得认证

开始吧
广告
© . All rights reserved.