Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
class NestedIterator {
public:
NestedIterator(vector<NestedInteger>& nestedList) { append(nestedList, q); }
void append(vector<NestedInteger>& nestedList, queue<int>& q) {
for (auto& x : nestedList) {
if (x.isInteger()) {
q.emplace(x.getInteger());
} else {
append(x.getList(), q);
}
}
}
int next() {
int res = q.front();
q.pop();
return res;
}
bool hasNext() { return !empty(q); }
private:
queue<int> q;
};