用队列实现栈和用栈实现队列 发表于 2018-08-03 | 分类于 常见算法 | 字数统计: 280 | 阅读时长 ≈ 2 用两个栈来实现队列,思路和用数组实现队列一样 12345678910111213141516171819202122232425262728293031323334353637383940//用栈实现队列struct QueueByStack{ var Peek: Int? { mutating middleCaulate() return rightStack?.peek } typealias Element = Int private var leftStack:IntergerStack? private var rightStack:IntergerStack? init() { leftStack = IntergerStack() rightStack = IntergerStack() } var isEmpty: Bool {return leftStack!.isEmpty && rightStack!.isEmpty} var Size: Int {return leftStack!.Size + rightStack!.Size} mutating func middleCaulate(){ if leftStack!.isEmpty { while !rightStack!.isEmpty{ leftStack!.push((rightStack?.pop())!) } } } mutating func enQueue(_ newElement: Int) { rightStack?.push(newElement) } mutating func deQueue() -> Int? { middleCaulate() return leftStack?.peek } } 用两个队列来实现栈 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849struct StackByQueue { private var queueA : IntergerQueue? private var queueB : IntergerQueue? init() { queueA = IntergerQueue() queueB = IntergerQueue() } var isEmpty: Bool{ get { return queueA!.isEmpty && queueB!.isEmpty } } var Size: Int { get { return queueA!.Size } } var peek: Int?{ mutating get { transfer() let obj = queueB?.Peek swap() return obj } } mutating func push(_ newElement:Int){ queueB?.enQueue(newElement) } mutating func pop()->Int?{ transfer() let obj = queueB?.deQueue() swap() return obj } mutating func transfer() { if queueB?.Size != 1{ queueA?.enQueue((queueB?.deQueue())!) } } mutating func swap(){ (queueA,queueB) = (queueB,queueA) }} -------评论系统采用disqus,如果看不到需要翻墙-------------