341.flatten-nested-list-iterator.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * // This is the interface that allows for creating nested lists.
  3. * // You should not implement it, or speculate about its implementation
  4. * function NestedInteger() {
  5. *
  6. * Return true if this NestedInteger holds a single integer, rather than a nested list.
  7. * @return {boolean}
  8. * this.isInteger = function() {
  9. * ...
  10. * };
  11. *
  12. * Return the single integer that this NestedInteger holds, if it holds a single integer
  13. * Return null if this NestedInteger holds a nested list
  14. * @return {integer}
  15. * this.getInteger = function() {
  16. * ...
  17. * };
  18. *
  19. * Return the nested list that this NestedInteger holds, if it holds a nested list
  20. * Return null if this NestedInteger holds a single integer
  21. * @return {NestedInteger[]}
  22. * this.getList = function() {
  23. * ...
  24. * };
  25. * };
  26. */
  27. Array.prototype.peek = function() {
  28. return this[this.length - 1]
  29. }
  30. /**
  31. * @constructor
  32. * @param {NestedInteger[]} nestedList
  33. */
  34. var NestedIterator = function(nestedList) {
  35. this.st = [nestedList]
  36. this.idx = [0]
  37. this.findNext()
  38. }
  39. /**
  40. * @this NestedIterator
  41. * @returns {boolean}
  42. */
  43. NestedIterator.prototype.hasNext = function() {
  44. return this.idx.length !== 0
  45. }
  46. /**
  47. * @this NestedIterator
  48. * @returns {integer}
  49. */
  50. NestedIterator.prototype.next = function() {
  51. let val = this.st.peek()[this.idx.peek()].getInteger()
  52. this.idx[this.idx.length-1]++
  53. this.findNext()
  54. return val
  55. }
  56. NestedIterator.prototype.findNext = function() {
  57. while (this.idx.length !== 0) {
  58. if (this.idx.peek() == this.st.peek().length) { // Out of bound
  59. this.idx.pop()
  60. this.st.pop()
  61. if (this.st.length !== 0) {
  62. this.idx[this.idx.length-1]++
  63. }
  64. } else if (!this.st.peek()[this.idx.peek()].isInteger()) { // Go into list
  65. this.st.push(this.st.peek()[this.idx.peek()].getList())
  66. this.idx.push(0)
  67. } else { // Found
  68. break
  69. }
  70. }
  71. }
  72. /**
  73. * Your NestedIterator will be called like this:
  74. * var i = new NestedIterator(nestedList), a = [];
  75. * while (i.hasNext()) a.push(i.next());
  76. */