Skip to content

Latest commit

 

History

History
79 lines (65 loc) · 2.53 KB

232.md

File metadata and controls

79 lines (65 loc) · 2.53 KB

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

2019-04-02 吴亲库里 库里的深夜食堂


✏️描述

使用栈来实现队列的以下操作.题目给的实例操作是这样的,第一次往队列推入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);
        }

联系