题目地址:
https://www.lintcode.com/problem/flatten-nested-list-iterator/description
给定一个嵌套整数的类,这个类要么是个整数,要么是个嵌套整数组成的列表。要求设计其迭代器,迭代其平铺开来后的所有整数。
思路是用栈,用类似于先序遍历多叉树的办法。初始化的时候先将nestedList逆序入栈。调用hasNext的时候,先判断一下栈顶是否是个整数;如果是,则返回true,否则将其pop出来,并且将pop出来的nestedList的NestedInteger逆序进栈;如此循环,直到栈顶是整数为止。如果栈最后变空了,说明没有整数了,返回false。也就是说,一旦调用hasNext,就要将下一个是整数的NestedInteger置于栈顶。调用next的时候直接pop掉栈顶返回即可。代码如下:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
public class NestedIterator implements Iterator<Integer> {
private Deque<NestedInteger> stack;
public NestedIterator(List<NestedInteger> nestedList) {
// Initialize your data structure here.
// 初始化一个栈,逆序将nestedList里的元素入栈
stack = new ArrayDeque<>();
for (int i = nestedList.size() - 1; i >= 0; i--) {
stack.push(nestedList.get(i));
}
}
// @return {int} the next element in the iteration
@Override
public Integer next() {
// Write your code here
return stack.pop().getInteger();
}
// @return {boolean} true if the iteration has more element or false
@Override
public boolean hasNext() {
// Write your code here
while (!stack.isEmpty()) {
// 看一下栈顶是否是整数,如果是,则返回true
NestedInteger top = stack.peek();
if (top.isInteger()) {
return true;
}
// 否则将栈顶弹出,并将它含的NestedInteger逆序入栈
stack.pop();
for (int i = top.getList().size() - 1; i >= 0; i--) {
stack.push(top.getList().get(i));
}
}
// 栈空了,说明没有下一个整数了,返回false
return false;
}
@Override
public void remove() {
stack.pop();
}
}
interface NestedInteger {
// @return true if this NestedInteger holds a single integer,
// rather than a nested list.
public boolean isInteger();
// @return the single integer that this NestedInteger holds,
// if it holds a single integer
// Return null if this NestedInteger holds a nested list
public Integer getInteger();
// @return the nested list that this NestedInteger holds,
// if it holds a nested list
// Return null if this NestedInteger holds a single integer
public List<NestedInteger> getList();
}
hasNext时间复杂度 O ( h ) O(h) O(h),next O ( 1 ) O(1) O(1)( h h h是树高)。空间复杂度 O ( h ) O(h) O(h)。