Very concise and easy-understanding Stack Solution by Java


  • 0
    S
    public class NestedIterator implements Iterator<Integer> {
        Stack<ListIterator<NestedInteger>> stack;
        NestedInteger cache;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            stack = new Stack<>();
            stack.push(nestedList.listIterator());
        }
    
        @Override
        public Integer next() {
            return cache.getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while (true) {
                if (stack.isEmpty()) break;
                if (!stack.peek().hasNext()) {
                    stack.pop();
                    continue;
                }
                
                cache = stack.peek().next();
                if (!cache.isInteger()) {
                    stack.push(cache.getList().listIterator());
                    continue;
                }
                
                return true;
            }
            return false;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.