From 5baecc0f7919912e10ea64651ddc880f8c61f3c9 Mon Sep 17 00:00:00 2001 From: SevenMonths Date: Fri, 27 May 2022 00:59:37 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0(0225.=E7=94=A8=E9=98=9F?= =?UTF-8?q?=E5=88=97=E5=AE=9E=E7=8E=B0=E6=A0=88.md)=EF=BC=9APHP=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0225.用队列实现栈.md | 78 +++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/problems/0225.用队列实现栈.md b/problems/0225.用队列实现栈.md index 3457c4b3..f946cd86 100644 --- a/problems/0225.用队列实现栈.md +++ b/problems/0225.用队列实现栈.md @@ -816,5 +816,83 @@ class MyStack { } ``` +PHP +> 双对列 +```php +// SplQueue 类通过使用一个双向链表来提供队列的主要功能。(PHP 5 >= 5.3.0, PHP 7, PHP 8) +// https://www.php.net/manual/zh/class.splqueue.php +class MyStack { + public $queueMain; // 保存数据 + public $queueTmp; // 辅助作用 + + function __construct() { + $this->queueMain=new SplQueue(); + $this->queueTmp=new SplQueue(); + } + + // queueMain: 1,2,3 <= add + function push($x) { + $this->queueMain->enqueue($x); + } + + function pop() { + $qmSize = $this->queueMain->Count(); + $qmSize --; + // queueMain: 3,2,1 => pop =>2,1 => add => 2,1 :queueTmp + while($qmSize --){ + $this->queueTmp->enqueue($this->queueMain->dequeue()); + } + // queueMain: 3 + $val = $this->queueMain->dequeue(); + // queueMain <= queueTmp + $this->queueMain = $this->queueTmp; + // 清空queueTmp,下次使用 + $this->queueTmp = new SplQueue(); + return $val; + } + + function top() { + // 底层是双链表实现:从双链表的末尾查看节点 + return $this->queueMain->top(); + } + + function empty() { + return $this->queueMain->isEmpty(); + } +} +``` +> 单对列 +```php +class MyStack { + public $queue; + + function __construct() { + $this->queue=new SplQueue(); + } + + function push($x) { + $this->queue->enqueue($x); + } + + function pop() { + $qmSize = $this->queue->Count(); + $qmSize --; + //queue: 3,2,1 => pop =>2,1 => add => 2,1,3 :queue + while($qmSize --){ + $this->queue->enqueue($this->queue->dequeue()); + } + $val = $this->queue->dequeue(); + return $val; + } + + function top() { + return $this->queue->top(); + } + + function empty() { + return $this->queue->isEmpty(); + } +} +``` -----------------------