添加(0232.用栈实现队列.md):PHP版本
This commit is contained in:
parent
91399c3aae
commit
8d3e5b4608
|
|
@ -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>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue