Really simple Java solution


  • 0
    A
    public class NestedIterator implements Iterator<Integer> {
    
        Stack<Integer> st;
        
        public NestedIterator(List<NestedInteger> nestedList) {
            st = new Stack<Integer>();
            flattenList(nestedList);
        }
        
        public void flattenList(List<NestedInteger> nestedList) {
            for(int i = nestedList.size() - 1; i >= 0; i--) {
                if(nestedList.get(i).isInteger()) {
                    st.push(nestedList.get(i).getInteger());
                } else {
                    flattenList(nestedList.get(i).getList());
                }
            }
        }
        
        @Override
        public Integer next() {
            return st.pop();
        }
    
        @Override
        public boolean hasNext() {
            return !st.isEmpty();
        }
    }
    

Log in to reply
 

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