aboutsummaryrefslogtreecommitdiff
path: root/flatten_nested_iterator.cpp
blob: 4a6f93cf03071116c8aaf04efb977eeb3574e164 (plain)
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
#include "leetcode.h"

class NestedIterator {
public:
  NestedIterator(vector<NestedInteger> &nestedList) {
    int n = nestedList.size();
    for (int i = n - 1; i >= 0; --i)
      nodes.push(nestedList[i]);
  }
  int next() {
    int ans = nodes.top().getInteger();
    nodes.pop();
    return ans;
  }
  bool hasNext() {
    while (!nodes.empty()) {
      NestedInteger curr = nodes.top();
      if (curr.isInteger())
        return true;
      nodes.pop();
      vector<NestedInteger> &adj = curr.getList();
      int n = adj.size();
      for (int i = n - 1; i >= 0; --i)
        nodes.push(adj[i]);
    }
    return false;
  }

private:
  stack<NestedInteger> nodes;
};

int main() {}