341. Flatten Nested List Iterator

https://leetcode.com/problems/flatten-nested-list-iterator/discuss/80147/Simple-Java-solution-using-a-stack-with-explanation

 

 1 public class NestedIterator implements Iterator<Integer> {
 2 
 3     Stack<NestedInteger> stack = new Stack<>();
 4     public NestedIterator(List<NestedInteger> nestedList) {
 5         for(int i = nestedList.size()-1; i >= 0 ; i--){
 6             stack.push(nestedList.get(i));
 7         }
 8         
 9     }
10 
11     @Override
12     public Integer next() {
13         return stack.pop().getInteger();
14     }
15 
16     @Override
17     public boolean hasNext() {
18         while(!stack.isEmpty()){
19             NestedInteger cur = stack.pop();
20             if(cur.isInteger()){
21                 stack.push(cur);
22                 return true;
23             }
24             for(int i = cur.getList().size()-1; i >= 0; i--){
25                 stack.push(cur.getList().get(i));
26             }
27         }
28         return false;
29     }
30 }

 

posted @ 2018-10-31 12:13  jasoncool1  阅读(137)  评论(0编辑  收藏  举报