SHARE
TWEET

Untitled

a guest May 26th, 2019 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class NestedIterator implements Iterator<Integer> {
  2.     private NestedInteger val;
  3.     private Stack<Iterator<NestedInteger>> its;
  4.    
  5.     public NestedIterator(List<NestedInteger> list) {
  6.         its = new Stack<>();
  7.        
  8.         its.push(list.iterator());
  9.        
  10.     }
  11.  
  12.     @Override
  13.     public Integer next() {
  14.         return val.getInteger();
  15.     }
  16.  
  17.     @Override
  18.     public boolean hasNext() {
  19.         while(!its.isEmpty()) {
  20.             Iterator<NestedInteger> it = its.peek();
  21.             if (!it.hasNext()) its.pop();
  22.             else {
  23.                 NestedInteger ni = it.next();
  24.                 if (ni.isInteger()) {
  25.                     val = ni;
  26.                     return true;
  27.                 } else {
  28.                     its.push(ni.getList().iterator());
  29.                 }
  30.             }
  31.         }
  32.        
  33.         return false;
  34.     }
  35. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top