Leetcode之PHP版题目解析(232. Implement Queue using Stacks)


2019-4-2 期二  

 Leetcode基础刷题之PHP解析(206. Reverse Linked List)

fcaf47a6b9e62139469668e90919b69d.png

使用栈来实现队列的以下操作.题目给的实例操作是这样的,第一次往队列推入1,第二次推入2,第三次返回队头,第四次删除队列头元素,最后判断当前队列是否为空.

题目已经让我们用栈来实现队列操作了.队列是先进先出(FIFO),栈是后进先出(LIFO),基于这个特点,我这里定义了两个数组用来存储栈,一个作为辅助的栈,每次把新push进来的数压入栈底,把最新的元素放在辅助栈的头部,然后弹出所有元素到另一个栈,那么另一个栈就能表示出队列元素的顺序了.

具体实现

       private  $arr1=[];
       private  $arr2=[];
       private  $front='';
     
    /**
     * Push element x to the back of queue.
     * @param Integer $x
     * @return NULL
     */
    function push($x) {
     if(empty($this->arr1)) {
         $this->front = $x;
     } 
        while(!empty($this->arr1)) {
            array_push($this->arr2,array_shift($this->arr1));
        }
        array_push($this->arr2,$x);
        while(!empty($this->arr2)) {
            array_push($this->arr1,array_shift($this->arr2));
        }
      
    }
  
    /**
     * Removes the element from in front of queue and returns that element.
     * @return Integer
     */
    function pop() {
       $index= array_shift($this->arr1);
        if(!empty($this->arr1)){
            $this->front = $this->arr1[0];
        }
        return $index;
    }
  
    /**
     * Get the front element.
     * @return Integer
     */
    function peek() {
        return $this->front;
    }
  
    /**
     * Returns whether the queue is empty.
     * @return Boolean
     */
    function empty() {
        return empty($this->arr1);
    }


Github整理地址:https://github.com/wuqinqiang/leetcode-php


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: Leetcode PHP题解--D22 806. Number of Lines To Write String

>> 下一篇: php小鲜肉们请看过来~~~