剑指offer php实现 用两个栈实现一个队列

题目

  • 用两个栈来实现一个队列,完成队列的PushPop操作。 队列中的元素为int类型。

题解

  • 初始化两个栈。
  • push:压入栈1。
  • pop:栈2不为空时,栈2出栈,栈2为空时,将栈1元素全部出栈压入栈2,栈2出栈。
<?php

class Queue
{
    public $queue;
    private $_queue;

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

    public function push($node)
    {
        $this->_queue->push($node);
    }

    public function pop()
    {
        if (!$this->queue->isEmpty()) {
            return $this->queue->pop();
        } else {
            while (!$this->_queue->isEmpty()) {
                $this->queue->push($this->_queue->pop());
            }
            return $this->queue->pop();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36431213/article/details/80226107
今日推荐