用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
知识点:栈后进先出,队列先进先出
var CQueue = function() {
this.stack1 = []
this.stack2 = []
};
CQueue.prototype.appendTail = function(value) {
this.stack1.push(value)
};
CQueue.prototype.deleteHead = function() {
if(this.stack2.length) {
return this.stack2.pop()
}
if(!this.stack1.length) return -1
while(this.stack1.length) {
this.stack2.push(this.stack1.pop())
}
return this.stack2.pop()
};
用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
示例:
输入:
[“MyStack”, “push”, “push”, “top”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
var MyStack = function() {
this.stack = []
}
MyStack.prototype.push = function(x) {
this.stack.push(x)
}
MyStack.prototype.top = function() {
if (!this.empty()) {
return this.stack[this.stack.length - 1]
}
}
MyStack.prototype.pop = function() {
if (!this.empty()) {
return this.stack.pop()
}
}
MyStack.prototype.empty = function() {
if (this.stack.length === 0) {
return true
} else {
return false
}
}