LeetCode题目-225

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2022-06-19 16:37:21

简介 LeetCode题目-225


✏Leetcode之PHP版题目解析(225. Implement Stack using Queues)


✏描述

使用队列来实现栈操作。


✏题目实例


✏题目分析

既然题目已经要求了,那么我们就不能直接简单粗暴的使用PHP的array_shift()和array_unshift().我这里定义了两个数组,来表示两个队列,然后利用一个辅助的变量就实现了利用队列来实现栈的操作。

        private $queue1=[];
            private $queue2=[];
         
           /**
            * Push element x onto stack.
            * @param Integer $x
            * @return NULL
            */
           function push($x) {
               array_push($this->queue2,$x);
               while(!empty($this->queue1)){
                   array_push($this->queue2,array_shift($this->queue1));
               }
               $temp=$this->queue1;
               $this->queue1=$this->queue2;
               $this->queue2=$temp;
           }
         
           /**
            * Removes the element on top of the stack and returns that element.
            * @return Integer
            */
           function pop() {
               return array_shift($this->queue1);
           }
         
           /**
            * Get the top element.
            * @return Integer
            */
           function top() {
               return current($this->queue1);
           }
         
           /**
            * Returns whether the stack is empty.
            * @return Boolean
            */
           function empty() {
               return empty($this->queue1)==true;
           }

转载链接:https://leetcode.cn/


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云