[栈] leetcode 341 Flatten Nested List Iterator
problem:https://leetcode.com/problems/flatten-nested-list-iterator/
这道题要手动维护栈,对于弱鸡的我写起来真痛苦Orz
class NestedIterator { public: vector<NestedInteger> list; NestedIterator(vector<NestedInteger> &nestedList) { list = nestedList; if(nestedList.size() != 0) sta.push({0, &list}); } stack<pair<int,vector<NestedInteger>*>> sta; int data; int next() { return data; } void advance() { if(sta.size() == 0) return; sta.top().first++; while(!sta.empty() && sta.top().first >= sta.top().second->size()) { sta.pop(); if(!sta.empty()) sta.top().first++; } } bool hasNext() { if(sta.size() == 0) return false; auto& cur = *sta.top().second; int idx = sta.top().first; if(cur[idx].isInteger()) { data = cur[idx].getInteger(); advance(); return true; } else { if(cur[idx].getList().size() > 0) { sta.push({0, &cur[idx].getList()}); if(hasNext()) return true; // 查找嵌套的 } advance(); // 跳到下一个 return hasNext(); // 查找相邻的 } } };