mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
@ -816,7 +816,6 @@ class MyStack {
|
||||
}
|
||||
```
|
||||
Scala:
|
||||
|
||||
使用两个队列模拟栈:
|
||||
```scala
|
||||
import scala.collection.mutable
|
||||
@ -897,6 +896,86 @@ class MyStack() {
|
||||
def empty(): Boolean = {
|
||||
queue.isEmpty
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
```
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user