统计总人数的链表以及case输出应该怎么写?
时间: 2024-02-22 17:59:55 浏览: 28
假设链表节点的定义为:
```c++
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
```
统计总人数的链表以及使用`switch case`语句输出的代码如下:
.h文件:
```c++
#ifndef STATISTICS_LIST_H
#define STATISTICS_LIST_H
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class StatisticsList {
public:
StatisticsList();
void addPerson();
int getTotal();
void clear();
private:
ListNode* head;
int total;
};
void printTotal(int total);
#endif
```
.cpp文件:
```c++
#include "statistics_list.h"
StatisticsList::StatisticsList() {
head = new ListNode(0);
total = 0;
}
void StatisticsList::addPerson() {
ListNode* curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = new ListNode(1);
total++;
}
int StatisticsList::getTotal() {
return total;
}
void StatisticsList::clear() {
ListNode* curr = head->next;
while (curr != NULL) {
ListNode* temp = curr;
curr = curr->next;
delete temp;
}
head->next = NULL;
total = 0;
}
void printTotal(int total) {
cout << "Total number of people: " << total << endl;
}
```
使用`switch case`语句输出可以这样写:
```c++
#include "statistics_list.h"
#include <iostream>
using namespace std;
int main() {
StatisticsList list;
int code;
while (true) {
cout << "1. Add person" << endl;
cout << "2. Get total" << endl;
cout << "3. Clear" << endl;
cout << "4. Exit" << endl;
cin >> code;
switch (code) {
case 1:
list.addPerson();
break;
case 2:
printTotal(list.getTotal());
break;
case 3:
list.clear();
break;
case 4:
return 0;
default:
cout << "Invalid code" << endl;
break;
}
}
}
```
此时运行程序,输入1即可添加一个人,输入2即可输出当前总人数,输入3即可清空链表,输入4即可退出程序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)