Very easy Java solution, like other iterator questions

  • 0

    I remember one iterator design question was using Deque, my solution for this question is also using Deque, just in a different way, that was used for Queue, this is for stack, nothing special actually.

    public class Vector2D implements Iterator<Integer> {
        Deque<Iterator<Integer>> stack;
        public Vector2D(List<List<Integer>> vec2d) {
            stack = new ArrayDeque();
            for (int i = vec2d.size() - 1; i >= 0; i--) {
                List<Integer> list = vec2d.get(i);
                if (list.iterator().hasNext()) {
        public Integer next() {
            Iterator<Integer> i = stack.pop();
            int res =;
            if (i.hasNext())
            return res;
        public boolean hasNext() {
            return !stack.isEmpty();

Log in to reply

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