C++计算链表size
时间: 2024-04-24 17:23:27 浏览: 16
要计算链表的大小,即链表中节点的总数,可以使用以下方法:
1. 创建一个计数器变量,并将其初始化为0。
2. 从链表的头节点开始,依次遍历每个节点。
3. 在每个节点处,将计数器加1。
4. 当遍历到链表的尾节点时,停止遍历。
5. 返回计数器的值作为链表的大小。
下面是一个示例代码,演示了如何计算链表的大小:
```c++
#include <iostream>
// 链表节点
struct Node {
int data;
Node* next;
};
// 计算链表大小
int calculateSize(Node* head) {
int size = 0;
Node* current = head;
while (current != nullptr) {
size++;
current = current->next;
}
return size;
}
int main() {
// 创建链表: 1 -> 2 -> 3 -> 4 -> nullptr
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};
head->next->next->next = new Node{4, nullptr};
// 计算链表大小
int size = calculateSize(head);
std::cout << "链表的大小为: " << size << std::endl;
// 释放链表内存
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}
return 0;
}
```
上述代码会输出链表的大小为4。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)