方法一:迭代法
注意入栈时,用的是反向迭代器rbegin,rend。
/**
* // 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 {
private:
stack<NestedInteger> st;
public:
NestedIterator(vector<NestedInteger> &nestedList) { //初始化,将整个整型链表放入栈中
for(auto iter=nestedList.rbegin();iter!=nestedList.rend();iter++)
st.push(*iter); //注意:用的是反向迭代器rbegin,rend!!!
}
int next() { //输出整数
NestedInteger top=st.top();
st.pop();
return top.getInteger();
}
bool hasNext() {
while(!st.empty()){ //栈不为空时
NestedInteger current=st.top();
if(current.isInteger()) //若栈顶元素为整数,则返回1用next输出该整数
return true;
st.pop(); //若栈顶为列表,则读出列表,将列表元素分别压入栈中
vector<NestedInteger> nestedList=current.getList();
for(auto iter=nestedList.rbegin();iter!=nestedList.rend();iter++)
st.push(*iter);
}
return false;
}
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/