• [LeetCode][JavaScript]Implement Queue using Stacks


    Implement Queue using Stacks 

    Implement the following operations of a queue using stacks.

    • push(x) -- Push element x to the back of queue.
    • pop() -- Removes the element from in front of queue.
    • peek() -- Get the front element.
    • empty() -- Return whether the queue is empty.
    Notes:
    • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
     
     
     

     
     
    2个栈实现队列。
    栈1为主,栈2为辅。
    push操作,先把栈2所有的元素都倒入栈1,然后对栈1压桟。
    pop和peek操作,如果栈2为空,就把栈1所有元素都倒入栈2,然后对栈2出桟。
     1 /**
     2  * @constructor
     3  */
     4 var Queue = function() {
     5     this.stack1 = [];
     6     this.stack2 = [];
     7 };
     8 
     9 /**
    10  * @param {number} x
    11  * @returns {void}
    12  */
    13 Queue.prototype.push = function(x) {
    14     var len = this.stack2.length;
    15     while(len--){
    16         this.stack1.push(this.stack2.pop());
    17     }
    18     this.stack1.push(x);
    19 };
    20 
    21 /**
    22  * @returns {void}
    23  */
    24 Queue.prototype.pop = function() {
    25     if(this.stack2.length === 0){
    26         var len = this.stack1.length;
    27         while(len--){
    28             this.stack2.push(this.stack1.pop());
    29         }
    30     }
    31     return this.stack2.pop();
    32 };
    33 
    34 /**
    35  * @returns {number}
    36  */
    37 Queue.prototype.peek = function() {
    38     if(this.stack2.length === 0){
    39         var len = this.stack1.length;
    40         while(len--){
    41             this.stack2.push(this.stack1.pop());
    42         }
    43     }
    44     return this.stack2[this.stack2.length - 1];
    45 };
    46 
    47 /**
    48  * @returns {boolean}
    49  */
    50 Queue.prototype.empty = function() {
    51     if(this.stack1.length === 0 && this.stack2.length === 0){
    52         return true;
    53     }
    54     return false;
    55 };
     
  • 相关阅读:
    LeetCode翻转矩阵后的得分-Python3<六>
    LeetCode子域名访问计数-Python3.7<五>
    LeetCode 键盘行-Python3.7<四>
    流程控制<二>
    Numbers、Strings、Lists 笔记<一>
    LeetCode-数组操作-Python<三>
    LeetCode链表相加-Python<二>
    LeetCode两数之和-Python<一>
    使用Django创建网站项目<二>
    Windows下vue-cli脚手架搭建入门<一>
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4628985.html
Copyright © 2020-2023  润新知