22 平面列表

原题网址:http://www.lintcode.com/zh-cn/problem/flatten-list/

给定一个列表,该列表中的每个要素要么是个列表,要么是整数。将其变成一个只包含整数的简单列表。

 注意事项

如果给定的列表中的要素本身也是一个列表,那么它也可以包含列表。

样例

给定 [1,2,[1,2]],返回 [1,2,1,2]

给定 [4,[3,[2,[1]]]],返回 [4,3,2,1]

挑战 

请用非递归方法尝试解答这道题。

 1 #include <iostream>
 2 #include <vector>
 3 #include <math.h>
 4 #include <string>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 
 9  class NestedInteger {
10     public:
11       // Return true if this NestedInteger holds a single integer,
12       // rather than a nested list.
13       bool isInteger() const;
14  
15       // Return the single integer that this NestedInteger holds,
16       // if it holds a single integer
17       // The result is undefined if this NestedInteger holds a nested list
18       int getInteger() const;
19  
20       // Return the nested list that this NestedInteger holds,
21       // if it holds a nested list
22       // The result is undefined if this NestedInteger holds a single integer
23      const vector<NestedInteger> &getList() const;
24 
25   };
26 
27  class Solution {
28  public:
29      // @param nestedList a list of NestedInteger
30      // @return a list of integer 
31  vector<int> result;
32   vector<int> flatten( const vector<NestedInteger> &nestedList)  //注意getList()返回const引用,接收变量也应为const引用,所以修改lintcode原来函数参数;
33   {
34      
35       int size=nestedList.size();
36       for (int i=0;i<size;i++)
37       {
38           if (nestedList[i].isInteger())
39           {
40               result.push_back(nestedList[i].getInteger());
41           }
42           else
43           {
44               flatten(nestedList[i].getList());
45           }
46       }
47       return result;
48   }
49  };
50   /*
51   //非递归;
52   vector<int> flatten(vector<NestedInteger> &nestedList)
53   {
54       vector<int> result;
55       int size=nestedList.size();
56 
57       for (int i=0;i<size;i++)
58       {
59           if (nestedList[i].isInteger())
60           {
61               result.push_back(nestedList[i].getInteger());
62           }
63           else
64           {
65               vector<NestedInteger> temp;
66               temp=nestedList[i].getList();
67           
68               while(temp.empty()==false)
69               {
70                   NestedInteger t=temp.back();
71                   temp.pop_back();
72                   if (t.isInteger())
73                   {
74                       result.push_back(t.getInteger());
75                   }
76                   else
77                   {
78                       
79                   }
80               }  
81           }
82       }
83       return result;
84   }*/

参考:

https://blog.csdn.net/yekongzhongdemeng/article/details/79310313

 

posted @ 2018-03-23 19:44  eeeeeeee鹅  阅读(157)  评论(0编辑  收藏  举报