Advertisement
nikunjsoni

341

Mar 26th, 2021
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 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.  
  19. class NestedIterator {
  20.     stack<NestedInteger> s;
  21. public:
  22.     NestedIterator(vector<NestedInteger> &nestedList) {
  23.         for(int i=nestedList.size()-1; i>=0; i--){
  24.             s.push(nestedList[i]);
  25.         }
  26.     }
  27.    
  28.     int next() {
  29.         int tmp = s.top().getInteger();
  30.         s.pop();
  31.         return tmp;
  32.     }
  33.    
  34.     bool hasNext() {
  35.         while(!s.empty()){
  36.             if(s.top().isInteger()) return true;
  37.             vector<NestedInteger> tmp = s.top().getList();
  38.             s.pop();
  39.             for(int i=tmp.size()-1; i>=0; i--)
  40.                 s.push(tmp[i]);
  41.         }
  42.         return false;
  43.     }
  44. };
  45.  
  46. /**
  47.  * Your NestedIterator object will be instantiated and called as such:
  48.  * NestedIterator i(nestedList);
  49.  * while (i.hasNext()) cout << i.next();
  50.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement