Java solution using a stack


  • 0
    Z
    public class NestedIterator implements Iterator<Integer> {
        private Stack<NestedInteger> st;
        public NestedIterator(List<NestedInteger> nestedList) {
            st = new Stack<NestedInteger>();
            for(int i=nestedList.size()-1;i>=0;i--) {
                st.push(nestedList.get(i));
            }
        }
    
        @Override
        public Integer next() {
            NestedInteger top = st.pop();
            return top.getInteger();
        }
    
        @Override
        public boolean hasNext() {
            while(!st.isEmpty() && !st.peek().isInteger()) {
                NestedInteger top = st.pop();
                for(int i=top.getList().size()-1;i>=0;i--) { 
                    NestedInteger cur = top.getList().get(i);
                    st.push(cur);
                }
            }
            return !st.isEmpty();
        }
    }

Log in to reply
 

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