题目描述
给定一个嵌套整数链表,请实现它的迭代器,用来遍历其中的所有整数。
嵌套链表中的每个元素,要么是一个整数,要么是嵌套链表。
样例1
给定链表 [[1,1],2,[1,1]],
重复调用`next()`函数,直到`hasNext()`返回`false`为止,我们会得到: [1,1,2,1,1]。
样例2
给定链表 [1,[4,[6]]],
重复调用`next()`函数,直到`hasNext()`返回`false`为止,我们会得到: [1,4,6].
算法
(dfs) $O(n)$
为了方便处理,在初始化时我们先递归遍历整个链表中的所有整数,将它们存入vector<int>
中。
dfs时,如果遇到整数,则直接存入数组中;如果遇到嵌套链表,则递归遍历之。
然后对于next()
函数,我们依次返回vector<int>
中的每个数;对于hasNext()
函数,我们判断是否已经遍历完整个vector<int>
;
时间复杂度分析:初始化时链表中的每个整数仅被遍历一次,所以初始化的时间复杂度是 $O(n)$;next()
函数每次返回一个数,时间复杂度是 $O(1)$;hasNext()
函数只有一个判断,时间复杂度也是 $O(1)$。
C++ 代码
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/
class NestedIterator {
public:
vector<int> seq;
int cnt = 0;
NestedIterator(vector<NestedInteger> &nestedList) {
dfs(nestedList);
}
void dfs(vector<NestedInteger> &nestedList)
{
for (auto t : nestedList)
{
if (t.isInteger()) seq.push_back(t.getInteger());
else
dfs(t.getList());
}
}
int next() {
return seq[cnt ++ ];
}
bool hasNext() {
return cnt < seq.size();
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/