1. 程式人生 > >232. 用棧實現佇列(JavaScript)

232. 用棧實現佇列(JavaScript)

使用棧實現佇列的下列操作:

  • push(x) -- 將一個元素放入佇列的尾部。
  • pop() -- 從佇列首部移除元素。
  • peek() -- 返回佇列首部的元素。
  • empty() -- 返回佇列是否為空。

示例:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // 返回 1
queue.pop();   // 返回 1
queue.empty(); // 返回 false

說明:

  • 你只能使用標準的棧操作 -- 也就是隻有 push to toppeek/pop from topsize
    , 和 is empty 操作是合法的。
  • 你所使用的語言也許不支援棧。你可以使用 list 或者 deque(雙端佇列)來模擬一個棧,只要是標準的棧操作即可。
  • 假設所有操作都是有效的 (例如,一個空的佇列不會呼叫 pop 或者 peek 操作)。

思路:

在JavaScript中,棧和佇列都用陣列來實現,但這裡只允許使用棧的操作,所以,只能使用如下操作。

a.push(x)       // 把x加入棧頂
a.pop()         // 出棧元素
a.length        // 棧的大小
a[a.length-1]   // 返回棧頂元素

對於push,棧和佇列操作一樣。

對於a.pop(),需要一個臨時棧temp,把 a 的所有元素都 pop 並 push 進 temp,然後將temp 棧頂元素 pop,最後把temp 所有元素都 pop 並 push 進 a。

對於a.peek,和 a.pop() 類似,只是不用將 temp 棧頂元素 pop,而是儲存temp[temp.length-1],並返回。

對於 a.empty,返回 a.length是否等於 0 即可。

/**
 * Initialize your data structure here.
 */
var MyQueue = function() {
  this.stack = [];
};

/**
 * Push element x to the back of queue. 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
  this.stack.push(x);
};

/**
 * Removes the element from in front of queue and returns that element.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
  var temp = [];
  for (var i = 0, size = this.stack.length; i < size; i++) {
    temp.push(this.stack.pop())
  }
  var pop = temp.pop()
  for (var j = 0, size = temp.length; j < size; j++) {
    this.stack.push(temp.pop())
  }
  return pop;
};

/**
 * Get the front element.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
  var temp = [];
  for (var i = 0, size = this.stack.length; i < size; i++) {
    temp.push(this.stack.pop())
  }
  var peek = temp[temp.length - 1];
  for (var j = 0, size = temp.length; j < size; j++) {
    this.stack.push(temp.pop())
  }
  return peek;
};

/**
 * Returns whether the queue is empty.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
  return this.stack.length === 0;
};

/** 
 * Your MyQueue object will be instantiated and called as such:
 * var obj = Object.create(MyQueue).createNew()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */