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 8d3e5b4

Browse files
committed
添加(0232.用栈实现队列.md):PHP版本
1 parent 91399c3 commit 8d3e5b4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

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

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,5 +496,49 @@ void myQueueFree(MyQueue* obj) {
496496
}
497497
```
498498
499+
PHP:
500+
```php
501+
// SplStack 类通过使用一个双向链表来提供栈的主要功能。[PHP 5 >= 5.3.0, PHP 7, PHP 8]
502+
// https://www.php.net/manual/zh/class.splstack.php
503+
class MyQueue {
504+
// 双栈模拟队列:In栈存储数据;Out栈辅助处理
505+
private $stackIn;
506+
private $stackOut;
507+
508+
function __construct() {
509+
$this->stackIn = new SplStack();
510+
$this->stackOut = new SplStack();
511+
}
512+
513+
// In: 1 2 3 <= push
514+
function push($x) {
515+
$this->stackIn->push($x);
516+
}
517+
518+
function pop() {
519+
$this->peek();
520+
return $this->stackOut->pop();
521+
}
522+
523+
function peek() {
524+
if($this->stackOut->isEmpty()){
525+
$this->shift();
526+
}
527+
return $this->stackOut->top();
528+
}
529+
530+
function empty() {
531+
return $this->stackOut->isEmpty() && $this->stackIn->isEmpty();
532+
}
533+
534+
// 如果Out栈为空,把In栈数据压入Out栈
535+
// In: 1 2 3 => pop push => 1 2 3 :Out
536+
private function shift(){
537+
while(!$this->stackIn->isEmpty()){
538+
$this->stackOut->push($this->stackIn->pop());
539+
}
540+
}
541+
}
542+
```
499543
-----------------------
500544
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

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