题目:设计一种数据结构,在前一个栈填满时新建一个栈,push()和pop()与普通栈的操作方法相同.
核心代码:
<pre><code>`class Stacks {
let maxSize:Int = 5
var bufferData:[[Int]] = []
func push(num:Int) {
if bufferData.count == 0 {
var data:[Int] = []
data.append(num)
bufferData.append(data)
} else {
var data:[Int]? = bufferData.last
if (data?.count)! < maxSize {
data?.append(num)
bufferData[bufferData.count - 1] = data!
} else {
var stack:[Int] = []
stack.append(num)
bufferData.append(stack)
}
}
}
func pop() -> Int? {
if bufferData.count == 0 {
return nil
}
var data:[Int] = bufferData.last!
var lastIndex:Int = bufferData.count - 1
if data.count == 0 {
if bufferData.count == 1 {
return nil
} else {
bufferData.removeLast()
lastIndex -= 1
data = bufferData[lastIndex]
}
}
let value:Int = data.last!
data.removeLast()
bufferData[lastIndex] = data
return value
}
}`</code></pre>
测试代码:
<pre><code>`var stacks:Stacks = Stacks()
for i in 0..<13 {
stacks.push(num: i)
}
print("(stacks.bufferData)")
for i in 0..<8 {
var value:Int? = stacks.pop()
if value != nil {
print("FlyElephant--Pop---(value!)")
}
}
print("(stacks.bufferData)")`</code></pre>
网友评论