实现思路:
利用递归的特性,如果返回的还是列表就遍历,直到返回的是一个整数,就将该整数压入到队列中,在实现next和hasNext操作的过程中,next操作直接返回队首并弹出,hasNext直接利用队列的特性,判断队列是否为空即可
实现代码:
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
// 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:
queue<int> re;
void push_data(vector<NestedInteger> nestedList) {
int n = nestedList.size();
for (int i = 0;i < n;i++) {
if (nestedList[i].isInteger()) re.push(nestedList[i].getInteger());
else {
push_data(nestedList[i].getList());
}
}
}
NestedIterator(vector<NestedInteger>& nestedList) {
push_data(nestedList);
}
int next() {
int t = re.front();
re.pop();
}
bool hasNext() {
return !re.empty();
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/
int main() {
return 0;
}
提交结果及分析:
next操作和hasNext操作的时间复杂度都是O(1),空间复杂度是O(n)