stack_2.由两个栈组成队列

思路:
用两个栈($stack_a, $stack_b),当push的时候,压入$stack_a, 让pop的时候,先把$stack_a元素依次全部倒入$stack_b中,再对$stack_b进行pop,然后再还原$stack_a,$stack_b(把$stack_b倒入stack_a)

<?php

class StackQueue
{
    public $stack_a;
    public $stack_b;

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

    public function pop()
    {
        $this->exchange($this->stack_a, $this->stack_b);
        $pop = $this->stack_b->pop();
        $this->exchange($this->stack_b, $this->stack_a);
        return $pop;
    }

    public function push($value)
    {
        $push = $this->stack_a->push($value);
        return $push;
    }

    public function exchange($stack_a, $stack_b)
    {
        $count = $stack_a->count();
        for ($i = 0; $i < $count; $i++) {
            $pop = $stack_a->pop();
            $stack_b->push($pop);
        }
    }
}

$StackQueue = new StackQueue();
$StackQueue->push(1);
$StackQueue->push(2);

echo $StackQueue->pop();
echo $StackQueue->pop();
posted @ 2017-02-03 20:08  Thomas_188  阅读(122)  评论(0编辑  收藏  举报