My concise and clean Java solution with Stack (10ms)

  • 0

    An Iterative DFS approach to traverse the nested list.

    Max space consumed would be the depth of the list.

    public class NestedIterator implements Iterator<Integer> {
        private Stack<NestedInteger> s;
        private NestedInteger p;
        public NestedIterator(List<NestedInteger> nestedList) {
            s = new Stack<NestedInteger>();
        public Integer next() {
            return p.getInteger();
        public boolean hasNext() {
            while (!s.isEmpty()) {
                p = s.pop();
                if (p.isInteger()) return true;
                else push(p.getList());
            return false;
        private void push(List<NestedInteger> nestedList) {
            for (int i = nestedList.size() - 1; i >= 0; --i) {

Log in to reply

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