[LeetCode] 341. Flatten Nested List Iterator Java
题目:
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]]
,
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]
.
Example 2:
Given the list [1,[4,[6]]]
,
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]
.
题意及分析:嵌套的list,要求给出其迭代器的next()和hasNext函数。可以使用一个stack来维护当前list剩余元素。我开始是在next里对stack做操作,但是由于当出现[]这种空list时没有办法判断hasNext,容易出现空指针操作。所以需要在hasNext()里面对stack操作。将list反向添加进stack中,这样就可以让先出现的数先被stack弹出。
代码:
public class NestedIterator implements Iterator<Integer> { List<NestedInteger> list; Stack<NestedInteger> stack = new Stack<>(); NestedInteger nowInteger; public NestedIterator(List<NestedInteger> nestedList) { list = nestedList; for(int i=list.size()-1;i>=0;i--){//对每一个list都反转 stack.push(list.get(i)); } } @Override public Integer next() { return stack.pop().getInteger(); } @Override public boolean hasNext() { if(stack.isEmpty()) return false; else{ nowInteger = stack.peek(); if(nowInteger.isInteger()){ return true; }else{ while(!stack.isEmpty()){ nowInteger=stack.pop(); List<NestedInteger> list = nowInteger.getList(); for(int i=list.size()-1;i>=0;i--){ stack.push(list.get(i)); } if(stack.isEmpty()) return false; //如果没有next直接返回false nowInteger = stack.peek(); //取出栈顶元素 if(nowInteger.isInteger()) return true; } } } return false; } }