341. Flatten Nested List Iterator

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

以上是关于341. Flatten Nested List Iterator的主要内容,如果未能解决你的问题,请参考以下文章

341. Flatten Nested List Iterator

341. Flatten Nested List Iterator

341. Flatten Nested List Iterator

LeetCode 341: Flatten Nested List Iterator

leetcode 341. Flatten Nested List Iterator

[leetcode] 341. Flatten Nested List Iterator