Advertisement
1988coder

341. Flatten Nested List Iterator

Jan 19th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/flatten-nested-list-iterator/
  3. import java.util.Iterator;
  4. import java.util.List;
  5. import java.util.NoSuchElementException;
  6. import java.util.Stack;
  7.  
  8. // This is the interface that allows for creating nested lists.
  9. // You should not implement it, or speculate about its implementation
  10. interface NestedInteger {
  11.  
  12.     // @return true if this NestedInteger holds a single integer, rather than a
  13.     // nested list.
  14.     public boolean isInteger();
  15.  
  16.     // @return the single integer that this NestedInteger holds, if it holds a
  17.     // single integer
  18.     // Return null if this NestedInteger holds a nested list
  19.     public Integer getInteger();
  20.  
  21.     // @return the nested list that this NestedInteger holds, if it holds a nested
  22.     // list
  23.     // Return null if this NestedInteger holds a single integer
  24.     public List<NestedInteger> getList();
  25. }
  26.  
  27. /**
  28.  * Using stack.
  29.  *
  30.  * Time Complexity: O(N)
  31.  *
  32.  * Space ComplexityL O(N)
  33.  *
  34.  * N = Total length of the nested list.
  35.  */
  36. class NestedIterator implements Iterator<Integer> {
  37.  
  38.     Stack<NestedInteger> stack = new Stack<>();
  39.  
  40.     public NestedIterator(List<NestedInteger> nestedList) {
  41.         if (nestedList == null) {
  42.             return;
  43.         }
  44.         flattenList(nestedList);
  45.     }
  46.  
  47.     @Override
  48.     public Integer next() throws NoSuchElementException {
  49.         if (!hasNext()) {
  50.             throw new NoSuchElementException("No next element");
  51.         }
  52.         return stack.pop().getInteger();
  53.     }
  54.  
  55.     @Override
  56.     public boolean hasNext() {
  57.         while (!stack.isEmpty()) {
  58.             if (stack.peek().isInteger()) {
  59.                 return true;
  60.             }
  61.             flattenList(stack.pop().getList());
  62.         }
  63.         return false;
  64.     }
  65.  
  66.     private void flattenList(List<NestedInteger> list) {
  67.         for (int i = list.size() - 1; i >= 0; i--) {
  68.             stack.push(list.get(i));
  69.         }
  70.     }
  71. }
  72.  
  73. // Your NestedIterator object will be instantiated and called as such:
  74. // NestedIterator i = new NestedIterator(nestedList);
  75. // while (i.hasNext()) v[f()] = i.next();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement