用两个栈实现队列

    用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )

    知识点:栈后进先出,队列先进先出

    1. var CQueue = function() {
    2. this.stack1 = []
    3. this.stack2 = []
    4. };
    5. CQueue.prototype.appendTail = function(value) {
    6. this.stack1.push(value)
    7. };
    8. CQueue.prototype.deleteHead = function() {
    9. if(this.stack2.length) {
    10. return this.stack2.pop()
    11. }
    12. if(!this.stack1.length) return -1
    13. while(this.stack1.length) {
    14. this.stack2.push(this.stack1.pop())
    15. }
    16. return this.stack2.pop()
    17. };

    用队列实现栈

    请你仅使用两个队列实现一个后入先出(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

    1. var MyStack = function() {
    2. this.stack = []
    3. }
    4. MyStack.prototype.push = function(x) {
    5. this.stack.push(x)
    6. }
    7. MyStack.prototype.top = function() {
    8. if (!this.empty()) {
    9. return this.stack[this.stack.length - 1]
    10. }
    11. }
    12. MyStack.prototype.pop = function() {
    13. if (!this.empty()) {
    14. return this.stack.pop()
    15. }
    16. }
    17. MyStack.prototype.empty = function() {
    18. if (this.stack.length === 0) {
    19. return true
    20. } else {
    21. return false
    22. }
    23. }