diff --git a/problems/0232.用栈实现队列.md b/problems/0232.用栈实现队列.md index 47993fa1..4662e2f2 100644 --- a/problems/0232.用栈实现队列.md +++ b/problems/0232.用栈实现队列.md @@ -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 } + } ``` -----------------------