[Swift]LeetCode341. 压平嵌套链表迭代器 $ Flatten Nested List Iterator
作者:互联网
Given a nested list of integers, implement an iterator to flatten it.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Example 1:
Given the list [[1,1],2,[1,1]]
,
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1]
.
Example 2:
Given the list [1,[4,[6]]]
,
By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6]
.
给定一个嵌套的整数列表,实现一个迭代器来展平它。
每个元素要么是一个整数,要么是一个列表——其元素也可以是整数或其他列表。
例1:
给出列表[[1,1],2,[1,1]],
通过反复调用next,直到hasNext返回false,next返回的元素顺序应该是:[1,1,2,1,1]。
例2:
给出清单[1,[4,[6]]],
通过重复调用next直到hasNext返回false,next返回的元素顺序应该是:[1,4,6]。
Solution:
1 class NestedIterator 2 { 3 var d:[NestedInteger] = [NestedInteger]() 4 init(_ nestedList:inout [NestedInteger]) 5 { 6 for a in nestedList 7 { 8 d.append(a) 9 } 10 } 11 12 func next() -> Int 13 { 14 var t:NestedInteger = d.removeFirst() 15 return t.getInteger() 16 } 17 18 func hasNext() -> Bool 19 { 20 while(!d.isEmpty) 21 { 22 var t:NestedInteger = d.first! 23 if t.isInteger() 24 { 25 return true 26 } 27 d.removeFirst() 28 for i in 0..<t.get.getList().count 29 { 30 d.insert(t.getList()[i],at:i) 31 } 32 } 33 return false 34 } 35 }
标签:hasNext,Iterator,LeetCode341,list,next,链表,NestedInteger,var,false 来源: https://www.cnblogs.com/strengthen/p/10738395.html