用两个栈来实现一个队列 php

思路:
定义一个栈为储存队列 queue, 一个为临时队列 tmp_queue
入列: 正常入栈
出列: 将 queue 依次 pop 出栈并 push 入栈到 tmp_queue, 根据栈特性 先进后出 然后把 tmp_queuepop 出第一个元素, 最后依次把 tmp_queue 的元素重新入栈回 queue
至此实现了队列的性质 先进先出

class Queue{
    public $queue;

    public function __construct(){
        $this->queue = new SplStack();
    }

	//入列
    public function push($data){
        $this->queue->push($data);
    }

	//出列
    public function pop(){
        if($this->queue->isEmpty())
            return false;
        
        $tmp_queue = new SplStack();
        while(!$this->queue->isEmpty()){
            $tmp_queue->push($this->queue->pop());
        }
        $data = $tmp_queue->pop();
        while(!$tmp_queue->isEmpty()){
            $this->queue->push($tmp_queue->pop());
        }
        return $data;
    }
}

#测试
echo '<pre>';
$list = new Queue();
$list->push(2);
$list->push(3);
$list->push(4);
$list->pop();
$list->push(5);
$list->pop();
print_r($list);





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值