題目: 數(shù)組實(shí)現(xiàn)椊韫颍可以彈性的分割也可以平均均分令境,按照平均分配的原則實(shí)現(xiàn)三個(gè)棧.
核心代碼:
<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>
測(cè)試代碼:
<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---棧號(hào)(i)---(j)---值:(String(describing: value!))")
}
}
}`</code></pre>