删一个之后还剩几个没归还
运行下面这段程序:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Node {
string name;
Node* next = nullptr;
};
int alive = 0; // 现在还有几个节点没有归还
Node* make(const string& name) {
alive++;
return new Node{name};
}
void drop(Node* nd) {
alive--;
delete nd;
}
Node* build(const vector<string>& names) {
Node* head = nullptr;
for (int i = (int)names.size() - 1; i >= 0; i--) {
Node* nd = make(names[i]);
nd->next = head;
head = nd;
}
return head;
}
int main() {
Node* head = build({"阿岚", "小满", "阿泰", "南风"});
Node* gone = head->next;
head->next = gone->next;
drop(gone);
cout << alive << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论