反转之后最后一个是谁
运行下面这段程序:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Node {
string name;
Node* next = nullptr;
};
Node* build(const vector<string>& names) {
Node* head = nullptr;
for (int i = (int)names.size() - 1; i >= 0; i--) {
Node* nd = new Node{names[i]};
nd->next = head;
head = nd;
}
return head;
}
int main() {
Node* head = build({"阿岚", "小满", "阿泰", "南风"});
Node* old_head = head;
Node* prev = nullptr;
Node* cur = head;
while (cur != nullptr) {
Node* nxt = cur->next;
cur->next = prev;
prev = cur;
cur = nxt;
}
cout << old_head->name << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论