参考:https://www.cnblogs.com/wanghui9072229/archive/2011/11/22/2259391.html
两个栈:$left 与 $right。$left用来进,$right用来出。
入队时,将元素压入$left。
出队时,判断$right是否为空,如不为空,则直接弹出顶元素;如为空,则将$left的元素逐个“倒入”$right,把最后一个元素弹出并出队。
<?php
class MyQueue {
public $left; //左进右出的左栈
private $right; //左进右出的右栈
/**
* Initialize your data structure here.
*/
function __construct() {
$this->left = new SplStack();
$this->right = new SplStack();
}
/**
* Push element x to the back of queue.
* @param Integer $x
* @return NULL
*/
function push($x) {
$this->left->push($x);
}
/**
* Removes the element from in front of queue and returns that element.
* @return Integer
*/
function pop() {
if (!$this->right->isEmpty()) {
return $this->right->pop();
} else {
while (!$this->left->isEmpty()) {
$this->right->push($this->left->pop());
}
return $this->right->pop();
}
}
/**
* Get the front element.
* @return Integer
*/
function peek() {
if (!$this->right->isEmpty()) {
return $this->right->top();
} else {
while (!$this->left->isEmpty()) {
$this->right->push($this->left->pop());
}
return $this->right->top();
}
}
/**
* Returns whether the queue is empty.
* @return Boolean
*/
function empty() {
return $this->left->isEmpty() && $this->right->isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* $obj = MyQueue();
* $obj->push($x);
* $ret_2 = $obj->pop();
* $ret_3 = $obj->peek();
* $ret_4 = $obj->empty();
*/