Skip to content

Commit abb903e

Browse files
committed
Merge branch 'master' of github.com:partho-maple/coding-interview-gym
* 'master' of github.com:partho-maple/coding-interview-gym: no message
2 parents 5f8c724 + 8131e3a commit abb903e

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
import Foundation
2+
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* // This is the interface that allows for creating nested lists.
3+
* // You should not implement it, or speculate about its implementation
4+
* class NestedInteger {
5+
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
6+
* public func isInteger() -> Bool
7+
*
8+
* // Return the single integer that this NestedInteger holds, if it holds a single integer
9+
* // The result is undefined if this NestedInteger holds a nested list
10+
* public func getInteger() -> Int
11+
*
12+
* // Set this NestedInteger to hold a single integer.
13+
* public func setInteger(value: Int)
14+
*
15+
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
16+
* public func add(elem: NestedInteger)
17+
*
18+
* // Return the nested list that this NestedInteger holds, if it holds a nested list
19+
* // The result is undefined if this NestedInteger holds a single integer
20+
* public func getList() -> [NestedInteger]
21+
* }
22+
*/
23+
24+
class NestedIterator {
25+
26+
var nestedListStack = [([NestedInteger], Int)]()
27+
28+
init(_ nestedList: [NestedInteger]) {
29+
self.nestedListStack.append((nestedList, 0))
30+
}
31+
32+
func next() -> Int {
33+
let (nestedList, currentIndex) = nestedListStack.removeLast()
34+
let result = nestedList[currentIndex].getInteger()
35+
nestedListStack.append((nestedList, currentIndex + 1))
36+
return result
37+
}
38+
39+
func hasNext() -> Bool {
40+
while !nestedListStack.isEmpty {
41+
let (nestedList, currentIndex) = nestedListStack.last!
42+
if currentIndex >= nestedList.count {
43+
nestedListStack.removeLast()
44+
} else {
45+
if nestedList[currentIndex].isInteger() {
46+
return true
47+
} else {
48+
nestedListStack[nestedListStack.count - 1] = (nestedList, currentIndex + 1)
49+
nestedListStack.append((nestedList[currentIndex].getList(), 0))
50+
}
51+
}
52+
}
53+
return false
54+
}
55+
}
56+
57+
/**
58+
* Your NestedIterator object will be instantiated and called as such:
59+
* let obj = NestedIterator(nestedList)
60+
* let ret_1: Int = obj.next()
61+
* let ret_2: Bool = obj.hasNext()
62+
*/

0 commit comments

Comments
 (0)