Java Solution By Stacking List Iterator

  • 1
    public class NestedIterator implements Iterator<Integer> {
        Stack<Iterator<NestedInteger>> st;
        NestedInteger cur;
        public NestedIterator(List<NestedInteger> nestedList) {
            st = new Stack();
        public Integer next() {
            return cur.getInteger();
        public boolean hasNext() {
            do {
                while (!st.empty() && !st.peek().hasNext()) st.pop();
                if (st.empty()) return false;
                for (cur = st.peek().next(); !cur.isInteger(); cur = st.peek().next()) {
                    if (!st.peek().hasNext()) break;
            } while (!cur.isInteger());
            return true;
    // 9ms

Log in to reply

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