Merge pull request #1405 from fmtvar/0232

添加(0232.用栈实现队列.md):PHP版本
This commit is contained in:
程序员Carl
2022-06-28 11:20:55 +08:00
committed by GitHub

View File

@ -495,6 +495,53 @@ void myQueueFree(MyQueue* obj) {
obj->stackOutTop = 0;
}
```
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());
}
}
}
```
Scala:
```scala
class MyQueue() {
@ -533,6 +580,7 @@ class MyQueue() {
def empty(): Boolean = {
stackIn.isEmpty && stackOut.isEmpty
}
}
```
-----------------------