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.
這題我做的時(shí)候就覺得要是能用遞歸就好了笛臣,但是由于一次只能next()取一個(gè)孕荠,所以不知咋辦了≈O郑看了一眼solutions,用了stack蚊夫,然后去健身了镣陕,健身的時(shí)候想到了绽媒,就是把get到的東西不停的往stack里push,剛才自己試著實(shí)現(xiàn)了一下傲霸,代碼基本跟答案一致疆瑰,但是我一開始想的是把hasNext里面的操作放到next()里面,但是那樣有個(gè)問題昙啄,如果是[[]]這種情況穆役,我最終返回了一個(gè)null,它結(jié)果是[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秘狞。