Guest User

Untitled

a guest
Jun 21st, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  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. /**
  28. * @constructor
  29. * @param {NestedInteger[]} nestedList
  30. */
  31. var NestedIterator = function(nestedList) {
  32.  
  33. };
  34.  
  35.  
  36. /**
  37. * @this NestedIterator
  38. * @returns {boolean}
  39. */
  40. NestedIterator.prototype.hasNext = function() {
  41.  
  42. };
  43.  
  44. /**
  45. * @this NestedIterator
  46. * @returns {integer}
  47. */
  48. NestedIterator.prototype.next = function() {
  49.  
  50. };
  51.  
  52. /**
  53. * Your NestedIterator will be called like this:
  54. * var i = new NestedIterator(nestedList), a = [];
  55. * while (i.hasNext()) a.push(i.next());
  56. */
  57.  
  58. var NestedIterator = function(nestedList) {
  59. var flattenArray = function(nestedList, list) {
  60. for (var i = 0; i < nestedList.length; i++) {
  61. if (nestedList[i].isInteger()) {
  62. list.push(nestedList[i].getInteger());
  63. } else {
  64. flattenArray(nestedList[i].getList(), list);
  65. }
  66. }
  67. };
  68.  
  69. this.list = [];
  70. this.index = -1;
  71. flattenArray(nestedList, this.list);
  72. };
  73.  
  74. NestedIterator.prototype.hasNext = function() {
  75. return this.index < this.list.length - 1;
  76. };
  77.  
  78. NestedIterator.prototype.next = function() {
  79. this.index++;
  80. return this.list[this.index];
  81. };
Add Comment
Please, Sign In to add comment