dengxinyi 6 năm trước cách đây
mục cha
commit
0e1832e1c4
1 tập tin đã thay đổi với 33 bổ sung7 xóa
  1. 33 7
      medium/341.flatten-nested-list-iterator.js

+ 33 - 7
medium/341.flatten-nested-list-iterator.js

@@ -24,30 +24,56 @@
  *     };
  * };
  */
+
+Array.prototype.peek = function() {
+    return this[this.length - 1]
+}
+
 /**
  * @constructor
  * @param {NestedInteger[]} nestedList
  */
 var NestedIterator = function(nestedList) {
-    
-};
-
+	this.st = [nestedList]
+	this.idx = [0]
+	this.findNext()
+}
 
 /**
  * @this NestedIterator
  * @returns {boolean}
  */
 NestedIterator.prototype.hasNext = function() {
-    
-};
+	return this.idx.length !== 0
+}
 
 /**
  * @this NestedIterator
  * @returns {integer}
  */
 NestedIterator.prototype.next = function() {
-    
-};
+	let val = this.st.peek()[this.idx.peek()].getInteger()
+	this.idx[this.idx.length-1]++
+	this.findNext()
+	return val
+}
+
+NestedIterator.prototype.findNext = function() {
+	while (this.idx.length !== 0) {
+		if (this.idx.peek() == this.st.peek().length) { // Out of bound
+			this.idx.pop()
+			this.st.pop()
+			if (this.st.length !== 0) {
+				this.idx[this.idx.length-1]++
+			}
+		} else if (!this.st.peek()[this.idx.peek()].isInteger()) { // Go into list
+			this.st.push(this.st.peek()[this.idx.peek()].getList())
+			this.idx.push(0)
+		} else { // Found
+			break
+		}
+	}
+}
 
 /**
  * Your NestedIterator will be called like this: