Two java solutions using stack deal with different situations.


  • 0
    Q
    1. If the system call more init than next:
            Stack<NestedInteger> stack = new Stack<NestedInteger>();
    
    	public FlattenNestedListIterator(List<NestedInteger> nestedList) {
    		for (int i = nestedList.size() - 1; i >= 0; i--) {
    			stack.push(nestedList.get(i));
    		}
    	}
    
    	@Override
    	public Integer next() {
    		return stack.pop().getInteger();
    	}
    
    	@Override
    	public boolean hasNext() {
    		if (stack.isEmpty())
    			return false;
    		else {
    			NestedInteger n = stack.peek();
    			if (n.isInteger())
    				return true;
    			else {
    				n = stack.pop();
    				List<NestedInteger> list = n.getList();
    				for (int i = list.size() - 1; i >= 0; i--) {
    					stack.push(list.get(i));
    				}
    				return this.hasNext();
    			}
    		}
    
    	}
    
    1. If the system call more next than init:
    	Stack<Integer> stack = new Stack<Integer>();
    
    	public FlattenNestedListIterator(List<NestedInteger> nestedList) {
    		Stack<NestedInteger> temp = new Stack<NestedInteger>();
    		for (int i = 0; i < nestedList.size() ; i++) {
    			temp.push(nestedList.get(i));
    		}
    		while(!temp.isEmpty()){
    			NestedInteger n = temp.pop();
    			if (n.isInteger()) stack.push(n.getInteger());
    			else{
    				List<NestedInteger> list = n.getList();
    				for (int i = 0; i < list.size(); i++) {
    					temp.push(list.get(i));
    				}
    			}
    		}
    		
    
    	}
    
    	@Override
    	public Integer next() {
    		return stack.pop();
    	}
    
    	@Override
    	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.