本文主要是介绍Flatten Nested List Iterator问题及解法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:
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 {
public: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;}
};
这篇关于Flatten Nested List Iterator问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!