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.
Notice
You don't need to implement the remove method.
Example
Given the list[[1,1],2,[1,1]], By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:[1,1,2,1,1].
Given the list[1,[4,[6]]], By calling next repeatedly until hasNext returns false, the order of elements returned by next should be:[1,4,6].
要用deque来把nested的list元素倒出来。中间还得用stack来保证顺序。
publicclassNestedIteratorimplementsIterator<Integer> {Deque<NestedInteger> deque =newLinkedList<>();publicNestedIterator(List<NestedInteger> nestedList) {for (NestedInteger ni : nestedList) {deque.offerLast(ni); } }// @return {int} the next element in the iteration @OverridepublicIntegernext() {returndeque.pollFirst().getInteger(); }// @return {boolean} true if the iteration has more element or false @OverridepublicbooleanhasNext() {if (deque.size() ==0) {returnfalse; } else {if (deque.peekFirst().isInteger()) {returntrue; } else {NestedInteger cur =deque.pollFirst();while (cur !=null&&!cur.isInteger()) {Stack<NestedInteger> stack =newStack<>();for (NestedInteger ni :cur.getList()) {stack.push(ni); }while (!stack.isEmpty()) {deque.offerFirst(stack.pop()); } cur =deque.pollFirst(); }if (cur !=null) {deque.offerFirst(cur);returntrue; }returnfalse; } } } @Overridepublicvoidremove() {}}