mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -495,6 +495,53 @@ void myQueueFree(MyQueue* obj) {
|
|||||||
obj->stackOutTop = 0;
|
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:
|
||||||
```scala
|
```scala
|
||||||
class MyQueue() {
|
class MyQueue() {
|
||||||
@ -533,6 +580,7 @@ class MyQueue() {
|
|||||||
def empty(): Boolean = {
|
def empty(): Boolean = {
|
||||||
stackIn.isEmpty && stackOut.isEmpty
|
stackIn.isEmpty && stackOut.isEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user