剑指 Offer 09.(用两个栈实现队列)

239 阅读1分钟

image.png

思路:由于需要用到两个栈,故将一个栈用于记录队列尾部,一个记录队列头部,每次只操作栈顶,无论进出。

var CQueue = function() {
  this.tail_stack=[]  // 这是记录队列尾部的栈
  this.head_stack=[]  // 这是记录队列头部的栈
};
/** 
 * @param {number} value
 * @return {void}
 */
CQueue.prototype.appendTail = function(value) {
   this.tail_stack.push(value)  // 当调用 appendTail 时就应该操作于 append_stack
};

/**
 * @return {number}
 */
CQueue.prototype.deleteHead = function() {

   // 难点当然在于操作函数里面
   // 步骤:
   // 1.假如 head_stack 为空,且 tail_stack 为空,该栈即为空栈,故输出 -1
   // 2.假如 head_stack 为空,但 tail_stack 非空,因此需要找到队首,再输出
   //    利用栈只操作栈顶的特性,将 tail_stack 倒置于 head_stack 中,直到 tail_stack 为空, 
   //    此时 head_stack 的栈便是按照队列从头到尾在栈顶到栈低排列
   // 3.假如 head_stack 非空,直接返回 head_stack 中的栈顶元素即可  
   
   
   
    if(!this.head_stack.length){
        if(!this.tail_stack.length){
            return -1
        }
        else{
            while(this.tail_stack.length){
                this.head_stack.push(this.tail_stack.pop())
            }
        }
    }
    return this.head_stack.pop()
};

/**
 * Your CQueue object will be instantiated and called as such:
 * var obj = new CQueue()
 * obj.appendTail(value)
 * var param_2 = obj.deleteHead()
 */