思路:
定義一個棧爲儲存隊列 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);