341. 扁平化嵌套列表迭代器
Posted yuhong1103
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了341. 扁平化嵌套列表迭代器相关的知识,希望对你有一定的参考价值。
1 /** 2 * // This is the interface that allows for creating nested lists. 3 * // You should not implement it, or speculate about its implementation 4 * class NestedInteger { 5 * public: 6 * // Return true if this NestedInteger holds a single integer, rather than a nested list. 7 * bool isInteger() const; 8 * 9 * // Return the single integer that this NestedInteger holds, if it holds a single integer 10 * // The result is undefined if this NestedInteger holds a nested list 11 * int getInteger() const; 12 * 13 * // Return the nested list that this NestedInteger holds, if it holds a nested list 14 * // The result is undefined if this NestedInteger holds a single integer 15 * const vector<NestedInteger> &getList() const; 16 * }; 17 */ 18 19 //看懂题意即可(其实就是列表的嵌套用深搜就行了) 20 class NestedIterator 21 { 22 public: 23 vector<int> v; 24 int index = 0; 25 26 NestedIterator(vector<NestedInteger> &nestedList) 27 { 28 dfs(nestedList); 29 } 30 31 int next() 32 { 33 return v[index++]; 34 } 35 36 bool hasNext() 37 { 38 if(index==v.size()) return false; 39 else return true; 40 } 41 42 void dfs(vector<NestedInteger> &nestedList) 43 { 44 for(int i=0;i<nestedList.size();i++) 45 { 46 if(nestedList[i].isInteger()) v.push_back(nestedList[i].getInteger()); 47 else dfs(nestedList[i].getList()); 48 } 49 } 50 }; 51 52 /** 53 * Your NestedIterator object will be instantiated and called as such: 54 * NestedIterator i(nestedList); 55 * while (i.hasNext()) cout << i.next(); 56 */
以上是关于341. 扁平化嵌套列表迭代器的主要内容,如果未能解决你的问题,请参考以下文章