题目
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1
输入:
["CQueue","appendTail","deleteHead","deleteHead","deleteHead"]
[[],[4],[],[],[]]
输出:[null,null,4,-1,-1]
示例2
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[3],[8],[],[]]
输出:[null,-1,null,null,3,8]
Swift
//用两个栈实现队列
//自定义栈结构
class AStack {
var list = [Int]()
func pop()-> Int{
if list.isEmpty == true {
//异常处理,返回-1
return -1
}
return list.removeLast()
}
func push(obj:Int) {
list.append(obj)
}
func isEmpty() -> Bool {
return list.isEmpty
}
}
class CQueue {
var inStack:AStack
var outStack:AStack
init() {
inStack = AStack()
outStack = AStack()
}
func appendTail(_ value: Int) {
inStack.push(obj: value)
}
func deleteHead() -> Int {
if outStack.isEmpty() == true {
while inStack.isEmpty() == false {
outStack.push(obj:inStack.pop())
}
}
return outStack.pop()
}
}
var que = CQueue()
que.appendTail(1)
que.deleteHead()
que.deleteHead()
que.deleteHead()
Java
待更新
对解法有疑问或者建议,可以留言哟
官网入口