22. 平面列表

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

易错点:nestedList.get(i).getInteger(),取集合中的元素时忘记get(i),,就取不到了

扩展:怎么用非递归来解答

思路:比较简单,直接递归调用即可。

  1. /** 
  2.  * // This is the interface that allows for creating nested lists. 
  3.  * // You should not implement it, or speculate about its implementation 
  4.  * public interface NestedInteger { 
  5.  * 
  6.  *     // @return true if this NestedInteger holds a single integer, 
  7.  *     // rather than a nested list. 
  8.  *     public boolean isInteger(); 
  9.  * 
  10.  *     // @return the single integer that this NestedInteger holds, 
  11.  *     // if it holds a single integer 
  12.  *     // Return null if this NestedInteger holds a nested list 
  13.  *     public Integer getInteger(); 
  14.  * 
  15.  *     // @return the nested list that this NestedInteger holds, 
  16.  *     // if it holds a nested list 
  17.  *     // Return null if this NestedInteger holds a single integer 
  18.  *     public List<NestedInteger> getList(); 
  19.  * } 
  20.  */  
  21. public class Solution {  
  22.   
  23.     // @param nestedList a list of NestedInteger  
  24.     // @return a list of integer  
  25.     public List<Integer> flatten(List<NestedInteger> nestedList) {  
  26.         // Write your code here  
  27.         List<Integer> list=new ArrayList<>();  
  28.         doFlatten(nestedList,list);  
  29.         return list;  
  30.     }  
  31.      public void doFlatten(List<NestedInteger> nestedList,List<Integer> list){  
  32.          if(nestedList != null){  
  33.              for(int i=0;i<nestedList.size();i++){  
  34.                  if(nestedList.get(i).isInteger()){  
  35.                      list.add(nestedList.get(i).getInteger());  
  36.                  }else{  
  37.                      doFlatten(nestedList.get(i).getList(),list);  
  38.                  }  
  39.              }  
  40.          }  
  41.      }  
  42. }  
 
原文地址:https://www.cnblogs.com/Pjson/p/8289426.html