#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class NestedInteger {
public:
NestedInteger(int i) : integer(i), isInt(true) {}
NestedInteger(vector l) : nestedList(l), isInt(false) {}
// Return true if this NestedInteger holds a single integer, rather than
a nested list.
bool isInteger() {
return isInt;
}
// Return the single integer that this NestedInteger holds, if it holds
a single integer
// The result is undefined if this NestedInteger holds a nested list
int getInteger() {
return integer;
}
// Return the nested list that this NestedInteger holds, if it holds a
nested list
// The result is undefined if this NestedInteger holds a single integer
vector &getList() {
return nestedList;
}
bool isInt;
int integer;
vector nestedList;
};
class NestedIntegerIterator {
public:
NestedIntegerIterator(vector &nestedList) {
s.push({nestedList.begin(), nestedList.end()});
}
int next() {
return (s.top()[0]++)->getInteger();
}
bool hasNext() {
while (!s.empty()) {
while (!s.empty() && s.top()[0] == s.top()[1]) {
s.pop();
if (!s.empty())
++s.top()[0];
}
if (!s.empty() && s.top()[0]->isInteger())
return true;
while (!s.empty() && !s.top()[0]->isInteger())
s.push({s.top()[0]->getList().begin(), s.top()[0]->getList()
.end()});
}
return false;
}
private:
stack::iterator>> s;
};
int main()
{
{
vector l = {NestedInteger(0), NestedInteger({
NestedInteger(1), NestedInteger(2)}), NestedInteger(3), NestedInteger({
NestedInteger(4), NestedInteger({NestedInteger(5), NestedInteger(6)})})};
NestedIntegerIterator ni(l);
while (ni.hasNext())
cout << ni.next() << endl;
}
return 0;
}