在C ++中查找链接列表的长度(迭代和递归)
在这里,我们将看到如何使用迭代和递归方法查找链表的长度。如果给出了头指针,我们必须遵循以下步骤来获取长度。
对于迭代方法-
以列表的开头,直到当前指针不为空,再转到下一个节点并增加计数。
对于递归方法-
将head作为参数传递,基本条件是参数为null时,然后返回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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短