算法与数据结构题目的 PHP 实现:栈和队列 由两个栈组成的队列

时间:2023-03-08 22:20:47

思路:同样使用 PHP 的数组模拟栈。栈的特点是先进后出,队列的特点是先进先出,可以用第一个栈(StackPush)作为压入栈,压入数据的时候只往这个栈中压入数据,第二个栈作(StackPop)为弹出栈,在弹出数据的时候只从这个栈中弹出。在弹出之前,把压入栈的数据全部 弹出至 弹出栈,再把弹出栈的数据弹出。

代码:

 <?php

 class TwoStacksQueue {
//压入栈
private $StackPush = array();
//弹出栈
private $StackPop = array(); //压入栈 压入数据
public function add($pushInt) {
array_push($this->StackPush, $pushInt);
} //将数据从压入栈 倒入 弹出栈
public function poll() {
if (empty($this->StackPush) && empty($this->StackPop)) {
echo 'Queue is empty.';
exit();
} else if (empty($this->StackPop)) {
while (!empty($this->StackPush)) {
$pop = array_pop($this->StackPush);
array_push($this->StackPop, $pop);
}
}
} //查看弹出栈的栈顶元素
public function peek() {
if (empty($this->StackPush) && empty($this->StackPop)) {
echo 'Queue is empty.';
exit();
} else if (empty($this->StackPop)) {
while (!empty($this->StackPush)) {
$pop = array_pop($this->StackPush);
array_push($this->StackPop, $pop);
}
}
$count = count($this->StackPop);
return $this->StackPop[$count - 1];
} //查看压入栈
public function getStackPush() {
return $this->StackPush;
} //查看弹出栈
public function getStackPop() {
return $this->StackPop;
}
} $queue = new TwoStacksQueue();
$queue->add(1);
$queue->add(2);
$queue->add(3);
$queue->add(4);
$queue->add(5);
var_dump($queue->getStackPush());
$queue->poll();
var_dump($queue->getStackPush());
var_dump($queue->getStackPop());
var_dump($queue->peek());

输出:

array
0 => int 1
1 => int 2
2 => int 3
3 => int 4
4 => int 5
array
empty
array
0 => int 5
1 => int 4
2 => int 3
3 => int 2
4 => int 1
int 1