Java solution, avoid push every integer into stack


  • 0
    J

    only push into stack when it's list

        class StackElement {
            List<NestedInteger> list;
            int index = -1;
            StackElement(List<NestedInteger> list) { this.list = list; }
        }
        
        Stack<StackElement> stack;
    
        public NestedIterator(List<NestedInteger> nestedList) {
            stack = new Stack<>();
            stack.push(new StackElement(nestedList));
        }
    
        @Override
        public Integer next() {
            return stack.peek().list.get(stack.peek().index).getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while (!stack.isEmpty()) {
                stack.peek().index++;
                if (stack.peek().index >= stack.peek().list.size()) stack.pop();
                else {
                    int index = stack.peek().index;
                    List<NestedInteger> list = stack.peek().list;
                    if (list.get(index).isInteger()) return true;
                    stack.push(new StackElement(list.get(index).getList()));
                }
            }
            return !stack.isEmpty();
        }
    

Log in to reply
 

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