题目: 数组实现栈可以弹性的分割也可以平均均分,按照平均分配的原则实现三个栈.
核心代码:
<pre><code>` let stackSize:Int = 10
var buffer:[Int?] = [Int?].init(repeating: nil, count: 30)
var stackPointer:[Int] = [-1, -1, -1]
func push(stackNum:Int,value:Int) {
if stackNum < 0 || stackNum >= stackPointer.count {
return
}
if stackPointer[stackNum] + 1 >= stackSize {
return
}
stackPointer[stackNum] += 1
buffer[absTopOfStack(stackNum: stackNum)] = value
}
func pop(stackNum:Int) -> Int? {
if stackNum < 0 || stackNum >= stackPointer.count {
return nil
}
if stackPointer[stackNum] == -1 {
return nil
}
let index:Int = absTopOfStack(stackNum: stackNum)
let value:Int? = buffer[index]
buffer[index] = nil
stackPointer[stackNum] -= 1
return value
}
func absTopOfStack(stackNum:Int) -> Int {
return stackNum * stackSize + stackPointer[stackNum]
}`</code></pre>
测试代码:
<pre><code>`var myStack:Stack = Stack()
for i in 10..<25 {
myStack.push(stackNum: 0, value: i)
}
for i in 30..<36 {
myStack.push(stackNum: 1, value: i)
}
for i in 40..<48 {
myStack.push(stackNum: 2, value: i)
}
for i in 0..<3 {
for j in 0..<10 {
var value:Int? = myStack.pop(stackNum: i)
if value != nil {
print("FlyElephant---栈号(i)---(j)---值:(String(describing: value!))")
}
}
}`</code></pre>
网友评论