A question before this is the Nested List Weight Sum, and it requires recursion to solve. As it carries to this problem that we will need recursion to solve it. But since we need to access each NestedInteger at a time, we will use a stack to help.
这题我做的时候就觉得要是能用递归就好了,但是由于一次只能next()取一个,所以不知咋办了。看了一眼solutions,用了stack,然后去健身了,健身的时候想到了,就是把get到的东西不停的往stack里push,刚才自己试着实现了一下,代码基本跟答案一致,但是我一开始想的是把hasNext里面的操作放到next()里面,但是那样有个问题,如果是[[]]这种情况,我最终返回了一个null,它结果是[null],而需要的是[]。
所以,堆栈操作要放在hashNext里。
Stack<NestedInteger> stack = new Stack<>();
public NestedIterator(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() {
while (!stack.isEmpty()) {
//不可以直接pop
NestedInteger ni = stack.peek();
if (ni.isInteger()) {
return true;
}
stack.pop();
List<NestedInteger> list = ni.getList();
for (int i = list.size() - 1; i >= 0; i--) {
stack.push(list.get(i));
}
}
return false;
}
有空做一下Nested List Weight Sum这题。
今天要熬夜做ppt。