[LeetCode][JavaScript]Implement Queue using Stacks

來源:互聯網
上載者:User

標籤:

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).
 https://leetcode.com/problems/implement-queue-using-stacks/     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} x11  * @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][JavaScript]Implement Queue using Stacks

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.