码迷,mamicode.com
首页 > 其他好文 > 详细

341. 扁平化嵌套列表迭代器

时间:2020-04-02 15:56:20      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:interface   const   and   tor   integer   题意   this   bool   bsp   

 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. 扁平化嵌套列表迭代器

标签:interface   const   and   tor   integer   题意   this   bool   bsp   

原文地址:https://www.cnblogs.com/yuhong1103/p/12619990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!