- ์ฌ๊ท ๊ตฌ์กฐ๋ก ๊ตฌํ๋ ์ซ์ ๋ชฉ๋ก์ ์ํํ๋ iterator๋ฅผ ๊ตฌํํ๋ ๋ฌธ์ .
- ํ์ฌ list์ ์์น๋ฅผ ์ ์ฅํ๋ ๊ฐ์ฒด
Entry
๋ฅผ ๋ง๋ค๊ณ stack
์ ์ฌ์ฉํ์ฌ ๊ฐ ์ค์ฒฉ๋ list์ ์์น ์ ๋ณด๋ฅผ ํํํ๋ค.
- List์์ ๋ค์ ์ซ์ ์์น๋ฅผ ๊ฐ๋ฆฌํค๋
Entry
๋ฅผ ์ฐพ๋ ํจ์ ensureNext
๋ฅผ ๊ตฌํํ๋ค. - Stack์ ๋ง์ง๋ง
Entry
๋ฅผ ๊ธฐ์ค์ผ๋ก - iterator๊ฐ ํ์ฌ list์ ๋ง์ง๋ง์ ๊ฐ๋ฆฌํค๋ ๊ฒฝ์ฐ stack์์ ์ ๊ฑฐํ๋ค.
- iterator๊ฐ ๊ฐ๋ฆฌํค๋ ํญ๋ชฉ์ด ์ซ์์ธ ๊ฒฝ์ฐ ํ์ฌ Entry๋ฅผ ๋๋ ค์ค๋ค.
- iterator๊ฐ ๊ฐ๋ฆฌํค๋ ํญ๋ชฉ์ด ๋ชฉ๋ก์ธ ๊ฒฝ์ฐ
- ์ฐธ์กฐ๋ฅผ ์ ์ฅํด๋๋ค
nextList
- iterator๋ฅผ ํ๋ ์ฆ๊ฐ์ํจ๋ค
- Stack์ nextList์ ๋ํ entry๋ฅผ ์ถ๊ฐํ๋ค.
hasNext
์์๋ ensureNext
์์ ๋๋ ค์ฃผ๋ entry๊ฐ ์กด์ฌ (not null)ํ๋์ง ํ์ธํ๋ค.
next
์์๋ ensureNext
์์ ๋๋ ค์ฃผ๋ entry์ ๊ฐ์ ์ฝ๊ณ entry์ iterator๋ฅผ ์ฆ๊ฐ์ํจ๋ค.
/**
* // 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 {
public:
using ListPtr = vector<NestedInteger>*;
using ListItr = vector<NestedInteger>::iterator;
using Entry = pair<ListPtr, ListItr>;
NestedIterator(vector<NestedInteger> &nestedList) {
entries.emplace_back(&nestedList, nestedList.begin());
}
int next() {
auto* entry = ensureNext();
if (entry == nullptr) return -1;
int result = entry->second->getInteger();
++(entry->second);
return result;
}
bool hasNext() {
return ensureNext() != nullptr;
}
Entry* ensureNext() {
while (!entries.empty()) {
auto& entry = entries.back();
if (entry.second == entry.first->end()) {
entries.pop_back();
continue;
}
if (entry.second->isInteger())
return &entry;
auto& nextList = entry.second->getList();
++entry.second;
entries.emplace_back(&nextList, nextList.begin());
}
return nullptr;
}
private:
vector<Entry> entries;
};
/**
* Your NestedIterator object will be instantiated and called as such:
* NestedIterator i(nestedList);
* while (i.hasNext()) cout << i.next();
*/