思路:
定义一个栈为储存队列 queue
, 一个为临时队列 tmp_queue
入列: 正常入栈
出列: 将 queue
依次 pop
出栈并 push
入栈到 tmp_queue
, 根据栈特性 先进后出
然后把 tmp_queue
中 pop
出第一个元素, 最后依次把 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);