Given a nested list of integers, implement an iterator to flatten it.html
Each element is either an integer, or a list -- whose elements may also be integers or other lists.數據結構
Example 1:
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]
. post
Example 2:
Given the list [1,[4,[6]]]
, url
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]
. spa
這道題讓咱們創建壓平嵌套鏈表的迭代器,關於嵌套鏈表的數據結構最先出如今Nested List Weight Sum中,而那道題是用的遞歸的方法來解的,而迭代器通常都是用迭代的方法來解的,而遞歸通常都需用棧來輔助遍歷,因爲棧的後進先出的特性,咱們在對向量遍歷的時候,從後往前把對象壓入棧中,那麼第一個對象最後壓入棧就會第一個取出來處理,咱們的hasNext()函數須要遍歷棧,並進行處理,若是棧頂元素是整數,直接返回true,若是不是,那麼移除棧頂元素,並開始遍歷這個取出的list,仍是從後往前壓入棧,循環中止條件是棧爲空,返回false,參見代碼以下:code
解法一:htm
class NestedIterator { public: NestedIterator(vector<NestedInteger> &nestedList) { for (int i = nestedList.size() - 1; i >= 0; --i) { s.push(nestedList[i]); } } int next() { NestedInteger t = s.top(); s.pop(); return t.getInteger(); } bool hasNext() { while (!s.empty()) { NestedInteger t = s.top(); if (t.isInteger()) return true; s.pop(); for (int i = t.getList().size() - 1; i >= 0; --i) { s.push(t.getList()[i]); } } return false; }
private: stack<NestedInteger> s; };
咱們也可使用deque來代替stack,實現思路和上面徹底同樣,參見代碼以下:對象
解法二:blog
class NestedIterator { public: NestedIterator(vector<NestedInteger> &nestedList) { for (auto a : nestedList) { d.push_back(a); } } int next() { NestedInteger t = d.front(); d.pop_front(); return t.getInteger(); } bool hasNext() { while (!d.empty()) { NestedInteger t = d.front(); if (t.isInteger()) return true; d.pop_front(); for (int i = 0; i < t.getList().size(); ++i) { d.insert(d.begin() + i, t.getList()[i]); } } return false; } private: deque<NestedInteger> d; };
雖然說迭代器是要用迭代的方法,可是咱們能夠強行使用遞歸來解,怎麼個強行法呢,就是咱們使用一個隊列queue,在構造函數的時候就利用迭代的方法把這個嵌套鏈表所有壓平展開,而後在調用hasNext()和next()就很簡單了:
解法三:
class NestedIterator { public: NestedIterator(vector<NestedInteger> &nestedList) { make_queue(nestedList); } int next() { int t = q.front(); q.pop(); return t; } bool hasNext() { return !q.empty(); } private: queue<int> q; void make_queue(vector<NestedInteger> &nestedList) { for (auto a : nestedList) { if (a.isInteger()) q.push(a.getInteger()); else make_queue(a.getList()); } } };
相似題目:
參考資料:
https://leetcode.com/discuss/95841/simple-solution-with-queue
https://leetcode.com/discuss/95892/concise-c-without-storing-all-values-at-initialization