Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 KB | None | 0 0
  1. /**
  2.  * // This is the interface that allows for creating nested lists.
  3.  * // You should not implement it, or speculate about its implementation
  4.  * class NestedInteger {
  5.  *   public:
  6.  *     // Return true if this NestedInteger holds a single integer, rather than a nested list.
  7.  *     bool isInteger() const;
  8.  *
  9.  *     // Return the single integer that this NestedInteger holds, if it holds a single integer
  10.  *     // The result is undefined if this NestedInteger holds a nested list
  11.  *     int getInteger() const;
  12.  *
  13.  *     // Return the nested list that this NestedInteger holds, if it holds a nested list
  14.  *     // The result is undefined if this NestedInteger holds a single integer
  15.  *     const vector<NestedInteger>& getList() const;
  16.  * };
  17.  */
  18. class NestedIterator {
  19. public:
  20.     NestedIterator(vector<NestedInteger>& nestedList) {
  21.         nested_int_stack_.push(&nestedList);
  22.         nested_int_pos_stack_.push(0);
  23.         MoveTillNextInteger();
  24.     }
  25.  
  26.     int next() {
  27.         MoveTillNextInteger();
  28.         return nested_int_stack_.top()->at(nested_int_pos_stack_.top()).getInteger();
  29.     }
  30.  
  31.     bool hasNext() {
  32.         MoveTillNextInteger();
  33.         return !nested_int_stack_.empty();
  34.     }
  35.    
  36. private:
  37.     stack<vector<NestedInteger>*> nested_int_stack_;
  38.     stack<int> nested_int_pos_stack_;
  39.    
  40.     void MoveTillNextInteger() {
  41.         int curr_pos = nested_int_pos_stack_.top();
  42.        
  43.         while (!nested_int_stack_.empty() && (curr_pos == nested_int_stack_.top()->size() ||
  44.                !nested_int_stack_.top()->at(curr_pos).isInteger())) {
  45.  
  46.             nested_int_pos_stack_.pop();
  47.  
  48.             if (curr_pos == nested_int_stack_.top()->size()) {
  49.                 nested_int_stack_.pop();
  50.                 curr_pos = nested_int_pos_stack_.top();
  51.                 continue;
  52.             }
  53.  
  54.             nested_int_pos_stack_.push(curr_pos + 1);
  55.             nested_int_stack_.push(&nested_int_stack_.top()->at(curr_pos).getList());
  56.             nested_int_pos_stack_.push(0);
  57.             curr_pos = 0;
  58.         }
  59.     }
  60. };
  61.  
  62. /**
  63.  * Your NestedIterator object will be instantiated and called as such:
  64.  * NestedIterator i(nestedList);
  65.  * while (i.hasNext()) cout << i.next();
  66.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement