难度:中等

    题目描述:
    给你一个嵌套的整型列表。请你设计一个迭代器,使其能够遍历这个整型列表中的所有整数。

    列表中的每一项或者为一个整数,或者是另一个列表。其中列表的元素也可能是整数或是其他列表。

    示例:

    1. 输入: [[1,1],2,[1,1]]
    2. 输出: [1,1,2,1,1]
    3. 解释: 通过重复调用 next 直到 hasNext 返回 falsenext 返回的元素的顺序应该是: [1,1,2,1,1]。

    解题思路:

    1. var NestedIterator = function(nestedList) {
    2. this.num = null;
    3. this.flag = false;
    4. this.stack = [];
    5. this.stack.push(nestedList);
    6. };
    7. NestedIterator.prototype.next = function() {
    8. this.flag = false;
    9. return this.num;
    10. };
    11. NestedIterator.prototype.hasNext = function() {
    12. if (!this.stack.length)
    13. return false;
    14. while (this.stack.length && !this.flag) {
    15. let temp = this.stack[this.stack.length - 1];
    16. if (temp.length) {
    17. let tt = temp.shift()
    18. if (tt.isInteger()) {
    19. this.num = tt.getInteger();
    20. this.flag = true;
    21. } else
    22. this.stack.push(tt.getList());
    23. } else {
    24. this.stack.pop();
    25. }
    26. }
    27. return this.flag;
    28. };