1. 程式人生 > >[leetcode]341. Flatten Nested List Iterator 展開巢狀列表的迭代器

[leetcode]341. Flatten Nested List Iterator 展開巢狀列表的迭代器

Given a nested list of integers, implement an iterator to flatten it.

Each element is either an integer, or a list -- whose elements may also be integers or other lists.

Example 1:

Input: [[1,1],2,[1,1]]
Output: [1,1,2,1,1]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next
should be: [1,1,2,1,1].

Example 2:

Input: [1,[4,[6]]]
Output: [1,4,6]
Explanation: By calling next repeatedly until hasNext returns false, 
             the order of elements returned by next should be: [1,4,6].

 

思路

 

程式碼

 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, rather than a nested list. 7 * public boolean isInteger(); 8 * 9 * // @return the single integer that this NestedInteger holds, if it holds a single integer
10 * // Return null if this NestedInteger holds a nested list 11 * public Integer getInteger(); 12 * 13 * // @return the nested list that this NestedInteger holds, if it holds a nested list 14 * // Return null if this NestedInteger holds a single integer 15 * public List<NestedInteger> getList(); 16 * } 17 */ 18 public class NestedIterator implements Iterator<Integer> { 19 20 private Stack<NestedInteger> stack; 21 22 public NestedIterator(List<NestedInteger> nestedList) { 23 stack = new Stack<>(); 24 pushListElements(nestedList); 25 } 26 27 @Override 28 public Integer next() { 29 return stack.pop().getInteger(); 30 } 31 32 @Override 33 public boolean hasNext() { 34 if (stack.isEmpty()) { 35 return false; 36 } 37 38 while (!stack.peek().isInteger()) { 39 pushListElements(stack.pop().getList()); 40 if (stack.isEmpty()) { 41 return false; 42 } 43 } 44 return true; 45 } 46 47 private void pushListElements(List<NestedInteger> list) { 48 for (int i = list.size() - 1; i >= 0; i--) { 49 stack.push(list.get(i)); 50 } 51 } 52 }