美文网首页
Swift-数组实现三个栈

Swift-数组实现三个栈

作者: FlyElephant | 来源:发表于2017-05-06 14:32 被阅读30次

    题目: 数组实现栈可以弹性的分割也可以平均均分,按照平均分配的原则实现三个栈.

    核心代码:
    <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>

    FlyElephant.png

    相关文章

      网友评论

          本文标题:Swift-数组实现三个栈

          本文链接:https://www.haomeiwen.com/subject/kynetxtx.html