Java solution, pre set next


  • 0
    X

    The only difference between my solution and most of others is I pre set the next so that it doesn't do anything if we just call hasNext().

    public class NestedIterator implements Iterator<Integer> {
    
    Stack<List<NestedInteger>> stack1;
    Stack<Integer> stack2;
    List<NestedInteger> cur1;
    int cur2;
    Integer next;
    
    public NestedIterator(List<NestedInteger> nestedList) {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
        cur1 = nestedList;
        cur2 = -1;
        next = null;
        update();
    }
    
    @Override
    public Integer next() {
        Integer result = next;
        update();
        return result;
    }
    
    @Override
    public boolean hasNext() {
        return next != null;
    }
    
    private void update() {
        next = null;
        cur2++;
        boolean found = false;
        boolean going = true;
        while (!found && going) {
            if (cur2 >= cur1.size()) {
                if (stack1.isEmpty()) {
                    going = false;
                } else {
                    cur1 = stack1.pop();
                    cur2 = stack2.pop();
                    cur2++;
                }
            } else {
                if (cur1.get(cur2).isInteger()) {
                    found = true;
                    next = cur1.get(cur2).getInteger();
                } else if (!cur1.get(cur2).getList().isEmpty()) {
                    stack1.push(cur1);
                    stack2.push(cur2);
                    cur1 = cur1.get(cur2).getList();
                    cur2 = 0;
                } else {
                    cur2++;
                }
            }
        }
    }
    

    }


Log in to reply
 

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