添加(0232.用栈实现队列.md):PHP版本

This commit is contained in:
SevenMonths
2022-05-26 13:09:05 +08:00
parent 91399c3aae
commit 8d3e5b4608

View File

@ -496,5 +496,49 @@ void myQueueFree(MyQueue* obj) {
}
```
PHP:
```php
// SplStack 类通过使用一个双向链表来提供栈的主要功能。[PHP 5 >= 5.3.0, PHP 7, PHP 8]
// https://www.php.net/manual/zh/class.splstack.php
class MyQueue {
// 双栈模拟队列In栈存储数据Out栈辅助处理
private $stackIn;
private $stackOut;
function __construct() {
$this->stackIn = new SplStack();
$this->stackOut = new SplStack();
}
// In: 1 2 3 <= push
function push($x) {
$this->stackIn->push($x);
}
function pop() {
$this->peek();
return $this->stackOut->pop();
}
function peek() {
if($this->stackOut->isEmpty()){
$this->shift();
}
return $this->stackOut->top();
}
function empty() {
return $this->stackOut->isEmpty() && $this->stackIn->isEmpty();
}
// 如果Out栈为空把In栈数据压入Out栈
// In: 1 2 3 => pop push => 1 2 3 :Out
private function shift(){
while(!$this->stackIn->isEmpty()){
$this->stackOut->push($this->stackIn->pop());
}
}
}
```
-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>