Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 634c051

Browse files
Merge pull request youngyangyang04#1405 from fmtvar/0232
添加(0232.用栈实现队列.md):PHP版本
2 parents d69eab3 + 6f0e93c commit 634c051

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎problems/0232.用栈实现队列.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,53 @@ void myQueueFree(MyQueue* obj) {
495495
obj->stackOutTop = 0;
496496
}
497497
```
498+
499+
500+
PHP:
501+
```php
502+
// SplStack 类通过使用一个双向链表来提供栈的主要功能。[PHP 5 >= 5.3.0, PHP 7, PHP 8]
503+
// https://www.php.net/manual/zh/class.splstack.php
504+
class MyQueue {
505+
// 双栈模拟队列:In栈存储数据;Out栈辅助处理
506+
private $stackIn;
507+
private $stackOut;
508+
509+
function __construct() {
510+
$this->stackIn = new SplStack();
511+
$this->stackOut = new SplStack();
512+
}
513+
514+
// In: 1 2 3 <= push
515+
function push($x) {
516+
$this->stackIn->push($x);
517+
}
518+
519+
function pop() {
520+
$this->peek();
521+
return $this->stackOut->pop();
522+
}
523+
524+
function peek() {
525+
if($this->stackOut->isEmpty()){
526+
$this->shift();
527+
}
528+
return $this->stackOut->top();
529+
}
530+
531+
function empty() {
532+
return $this->stackOut->isEmpty() && $this->stackIn->isEmpty();
533+
}
534+
535+
// 如果Out栈为空,把In栈数据压入Out栈
536+
// In: 1 2 3 => pop push => 1 2 3 :Out
537+
private function shift(){
538+
while(!$this->stackIn->isEmpty()){
539+
$this->stackOut->push($this->stackIn->pop());
540+
}
541+
}
542+
}
543+
```
544+
498545
Scala:
499546
```scala
500547
class MyQueue() {
@@ -533,6 +580,7 @@ class MyQueue() {
533580
def empty(): Boolean = {
534581
stackIn.isEmpty && stackOut.isEmpty
535582
}
583+
536584
}
537585
```
538586
-----------------------

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /