2つのスタックで1つのキューphpを実現
6757 ワード
:
は、貯蔵キューqueue
として定義され、1つは一時キュー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 ''
;
$list = new Queue();
$list->push(2);
$list->push(3);
$list->push(4);
$list->pop();
$list->push(5);
$list->pop();
print_r($list);