Solution in which hasNext() won't change the state of the stack. 7ms


  • 0
    Z

    In most solutions, hasNext() will change the state of the stack. In some situation, people won't use hasNext() before using next(). In most solutions, next() method will always return the same value.

    In my solution, you can use next() directly without using hasNext(). Also, hasNext() won't change the state of the stack at all.

    public class NestedIterator implements Iterator<Integer> {
    	
        private Stack<Iterator<NestedInteger>> stack;
        private Integer cur;
    	
        public NestedIterator(List<NestedInteger> nestedList) {
            stack = new Stack();
    	Iterator<NestedInteger> i = nestedList.iterator();
    	stack.push(i);
    	rearrange();
        }
    
        @Override
        public Integer next() {
            Integer num = cur;
            rearrange();
            return num;
        }
    
        @Override
        public boolean hasNext() {
            return !stack.isEmpty();
        }
        
        private void rearrange(){
            Iterator<NestedInteger> i;
            while(!stack.isEmpty()){
    	    i = stack.peek();
    	    if(i.hasNext()){
    		NestedInteger n = i.next();
    		if(n.isInteger()){
    		    cur = n.getInteger();
    		    break;
    		}
    		else{
    		    stack.push(n.getList().iterator());
    		}
    	    }
    	    else{
    	        stack.pop();
    	    }
            }
        }
    }
    

Log in to reply
 

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