Share my java solution


  • 0
    C

    public class NestedIterator implements Iterator<Integer> {

    Stack<ListIterator<NestedInteger>> stack = null;
    
    public NestedIterator(List<NestedInteger> nestedList) {
    	stack = new Stack<>();
    	stack.push(nestedList.listIterator());
    }
    
    @Override
    public Integer next() {
    	Iterator<NestedInteger> it = stack.peek();
    	NestedInteger item = it.next();
    	if(item.isInteger())
    		return item.getInteger();
    	else{
    		stack.push(item.getList().listIterator());
    		return next();
    	}
    	
    }
    
    @Override
    public boolean hasNext() {
    	if(stack.isEmpty()){
    		return false;
    	}
    	else{
    		ListIterator<NestedInteger> it = stack.peek();
    		if(it.hasNext()){
    			NestedInteger item = it.next();
    			if(item.isInteger()){
    				it.previous();
    				return true;
    			}
    			else{
    				stack.push(item.getList().listIterator());
    				return hasNext();
    			}
    		}
    		else {
    			stack.pop();
    			return hasNext();
    		}
    	}
    	
    }
    

    }


Log in to reply
 

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