链表取第三个走了几步
运行下面这段程序,它数的是「从头走了几步」:
#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* cur = head;
int steps = 0;
for (int i = 0; i < 2; i++) {
cur = cur->next;
steps++;
}
cout << steps << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论