开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 N 天,点击查看活动详情
给你一个嵌套的整数列表 nestedList 。每个元素要么是一个整数,要么是一个列表;该列表的元素也可能是整数或者是其他列表。请你实现一个迭代器将其扁平化,使之能够遍历这个列表中的所有整数。
实现扁平迭代器类 NestedIterator :
NestedIterator(List<NestedInteger> nestedList) 用嵌套列表 nestedList 初始化迭代器。
int next() 返回嵌套列表的下一个整数。
boolean hasNext() 如果仍然存在待迭代的整数,返回 true ;否则,返回 false 。
你的代码将会用下述伪代码检测:
initialize iterator with nestedList res = [] while iterator.hasNext() append iterator.next() to the end of res return res
如果 res 与预期的扁平化列表匹配,那么你的代码将会被判为正确。
示例 1:
输入:nestedList = [[1,1],2,[1,1]] 输出:[1,1,2,1,1] 解释:通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,1,2,1,1]。
示例 2:
输入:nestedList = [1,[4,[6]]] 输出:[1,4,6] 解释:通过重复调用 next 直到 hasNext 返回 false,next 返回的元素的顺序应该是: [1,4,6]。
提示:
1 <= nestedList.length <= 500
嵌套列表中的整数值在范围 [-106, 106] 内
栈解法
栈像一个劳改营,元素从后往前一个个入栈(前面元素后进去,栈后进先出,Next能先拿到前面元素),进栈了大家暂时相安无事。
等到Next调用时,要拿integer了,才忙活起来,整顿一下栈顶
审查一下栈顶元素,是integer就没事,是嵌套list 就pop出来,把它里面的元素一个个再塞入栈
有可能新的栈顶还不是 integer,继续上述操作,直到栈顶是 integer 或栈空了
这样整顿后,要么栈空了,要么栈顶一定是integer了
Stack []*NestedInteger
}
func Constructor(nestedList []*NestedInteger) *NestedIterator {
stack := []*NestedInteger{}
for i := len(nestedList) - 1; i >= 0; i-- {
stack = append(stack, nestedList[i])
}
return &NestedIterator{Stack: stack}
}
func (this *NestedIterator) Next() int {
this.stackTop2Integer()
top := this.Stack[len(this.Stack)-1]
return top.GetInteger()
}
func (this *NestedIterator) HasNext() bool {
this.stackTop2Integer()
return len(this.Stack) > 0
}
func (this *NestedIterator) stackTop2Integer() {
for len(this.Stack) > 0 {
top := this.Stack[len(this.Stack)-1]
if top.IsInteger() {
return
}
this.Stack = this.Stack[:len(this.Stack)-1]
list := top.GetList()
for i := len(list) - 1; i >= 0; i-- { list
this.Stack = append(this.Stack, list[i])
}
}
}