-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNestedIterator.cpp
More file actions
47 lines (43 loc) · 1.16 KB
/
NestedIterator.cpp
File metadata and controls
47 lines (43 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class NestedIterator {
public:
NestedIterator(vector<NestedInteger> &nestedList) {
for (int i = nestedList.size() - 1; i >= 0; --i)
st.push(nestedList[i]);
}
int next() {
NestedInteger cur = st.top(); st.pop();
return cur.getInteger();
}
bool hasNext() {
while (!st.empty()) {
NestedInteger cur = st.top();
if (cur.isInteger()) return true;
st.pop();
for (int i = cur.getList().size() - 1; i >= 0; --i)
st.push(cur.getList()[i]);
}
return false;
}
private:
stack<NestedInteger> st;
};
class NestedIterator {
public:
deque<int> q;
NestedIterator(vector<NestedInteger> &nestedList) {
std::function<void(vector<NestedInteger>)> dfs = [&](vector<NestedInteger> nestedList){
for(const auto& x : nestedList){
if(x.isInteger()) q.push_back(x.getInteger());
else dfs(x.getList());
}
};
dfs(nestedList);
}
int next() {
int ret = q.front(); q.pop_front();
return ret;
}
bool hasNext() {
return q.size();
}
};