我开始想错了。
    正确解法应该是创建一个Stack<NestedInteger> stack把所有的元素都放进去,然后不断的pop()

    • 如果是Integer,就返回
    • 如果是NestedInteger,就再把这个的Listpush()stack

    代码如下:

    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. Stack<NestedInteger> stack = new Stack<>();
    20. public NestedIterator(List<NestedInteger> nestedList) {
    21. pushHelper(nestedList);
    22. }
    23. @Override
    24. public Integer next() {
    25. return stack.pop().getInteger();
    26. }
    27. @Override
    28. public boolean hasNext() {
    29. while (!stack.empty()) {
    30. NestedInteger tmp = stack.peek();
    31. if (tmp.isInteger()) {
    32. break;
    33. }
    34. else {
    35. stack.pop();
    36. pushHelper(tmp.getList());
    37. }
    38. }
    39. return !stack.empty();
    40. }
    41. private void pushHelper(List<NestedInteger> nestedList) {
    42. for (int i = nestedList.size() - 1; i >= 0; --i) {
    43. stack.push(nestedList.get(i));
    44. }
    45. }
    46. }
    47. /**
    48. * Your NestedIterator object will be instantiated and called as such:
    49. * NestedIterator i = new NestedIterator(nestedList);
    50. * while (i.hasNext()) v[f()] = i.next();
    51. */