Lintcode 摊平嵌套的列表

Posted tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Lintcode 摊平嵌套的列表相关的知识,希望对你有一定的参考价值。

 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,
 7  *     // rather than a nested list.
 8  *     bool isInteger() const;
 9  *
10  *     // Return the single integer that this NestedInteger holds,
11  *     // if it holds a single integer
12  *     // The result is undefined if this NestedInteger holds a nested list
13  *     int getInteger() const;
14  *
15  *     // Return the nested list that this NestedInteger holds,
16  *     // if it holds a nested list
17  *     // The result is undefined if this NestedInteger holds a single integer
18  *     const vector<NestedInteger> &getList() const;
19  * };
20  */
21 class NestedIterator {
22 public:
23     vector<int> v;
24     int cnt;
25     int nested_size;
26     NestedIterator(vector<NestedInteger> &nestedList) {
27         // Initialize your data structure here.
28         v.clear();
29         cnt = 0;
30         dfs(nestedList);
31         nested_size = v.size();
32     }
33 
34     // @return {int} the next element in the iteration
35     int next() {
36         // Write your code here
37         return v[cnt++];
38     }
39 
40     // @return {boolean} true if the iteration has more element or false
41     bool hasNext() {
42         // Write your code here
43         if(nested_size){
44                 nested_size = nested_size - 1;
45                 return true;
46         } else {
47                 return false;
48         }
49     }
50 
51         void dfs(vector<NestedInteger> nestedList){
52                 for(int i = 0; i < nestedList.size(); ++i){
53                         if(nestedList[i].isInteger()){
54                                 v.push_back(nestedList[i].getInteger());
55                         } else {
56                                 dfs(nestedList[i].getList());
57                         }
58                 }
59         }
60 };
61 /**
62  * Your NestedIterator object will be instantiated and called as such:
63  * NestedIterator i(nestedList);
64  * while (i.hasNext()) v.push_back(i.next());
65  */

 

以上是关于Lintcode 摊平嵌套的列表的主要内容,如果未能解决你的问题,请参考以下文章

Python代码阅读(第41篇):矩阵转置

将片段添加到片段中(嵌套片段)

使用嵌套片段和动画对象

Android 动画嵌套片段

C#UWP填充和访问嵌套列表

“疫”考之下,大数据分析被“摊平”的春运