Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * // This is the interface that allows for creating nested lists.
- * // You should not implement it, or speculate about its implementation
- * class NestedInteger {
- * public:
- * // Return true if this NestedInteger holds a single integer, rather than a nested list.
- * bool isInteger() const;
- *
- * // 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() const;
- *
- * // 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
- * const vector<NestedInteger>& getList() const;
- * };
- */
- class NestedIterator {
- public:
- NestedIterator(vector<NestedInteger>& nestedList) {
- nested_int_stack_.push(&nestedList);
- nested_int_pos_stack_.push(0);
- MoveTillNextInteger();
- }
- int next() {
- MoveTillNextInteger();
- return nested_int_stack_.top()->at(nested_int_pos_stack_.top()).getInteger();
- }
- bool hasNext() {
- MoveTillNextInteger();
- return !nested_int_stack_.empty();
- }
- private:
- stack<vector<NestedInteger>*> nested_int_stack_;
- stack<int> nested_int_pos_stack_;
- void MoveTillNextInteger() {
- int curr_pos = nested_int_pos_stack_.top();
- while (!nested_int_stack_.empty() && (curr_pos == nested_int_stack_.top()->size() ||
- !nested_int_stack_.top()->at(curr_pos).isInteger())) {
- nested_int_pos_stack_.pop();
- if (curr_pos == nested_int_stack_.top()->size()) {
- nested_int_stack_.pop();
- curr_pos = nested_int_pos_stack_.top();
- continue;
- }
- nested_int_pos_stack_.push(curr_pos + 1);
- nested_int_stack_.push(&nested_int_stack_.top()->at(curr_pos).getList());
- nested_int_pos_stack_.push(0);
- curr_pos = 0;
- }
- }
- };
- /**
- * Your NestedIterator object will be instantiated and called as such:
- * NestedIterator i(nestedList);
- * while (i.hasNext()) cout << i.next();
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement