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  */

 

posted @ 2017-09-13 00:45 GeniusYang 阅读(...) 评论(...) 编辑 收藏