您的位置:首页 > 其它

Flatten Nested List Iterator问题及解法

2017-09-21 09:53 357 查看
问题描述:

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

示例:

Given the list 
[[1,1],2,[1,1]]
,

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: 
[1,1,2,1,1]
.

Given the list 
[1,[4,[6]]]
,

By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: 
[1,4,6]
.
问题分析:

将nestedlist中的值倒序存在stack中,对stack的首元素进行分析,若为整数,则可以输出,若还是nestedlist,重复前面的操作。

过程详见代码:

class NestedIterator {
pu
9d98
blic:

stack<NestedInteger> s;
NestedIterator(vector<NestedInteger>& nestedList) {
for (int i = nestedList.size() - 1; i >= 0; i--)
{
s.push(nestedList[i]);
}
}

int next() {
int res = s.top().getInteger();
s.pop();
return res;
}

bool hasNext() {
while (!s.empty())
{
NestedInteger t = s.top();
if (t.isInteger()) return true;
s.pop();
vector<NestedInteger>& adjs = t.getList();
for (int i = adjs.size() - 1; i >= 0; i--)
{
s.push(adjs[i]);
}
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: