-
Notifications
You must be signed in to change notification settings - Fork 17
/
stack_queue.php
69 lines (63 loc) · 1.31 KB
/
stack_queue.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
/**
* 通过两个栈实现队列
* Author: 学院君
*/
class StackQueue
{
/**
* 用于push数据
* @var SplStack
*/
protected $stack1;
/**
* 用于pop数据
* @var SplStack
*/
protected $stack2;
public function __construct()
{
$this->stack1 = new SplStack();
$this->stack2 = new SplStack();
}
/**
* 往队列中添加队尾元素
* @param $value
*/
public function pushToTail($value)
{
$this->stack1->push($value);
}
/**
* 从队列中删除队头元素
* @return mixed
* @throws Exception
*/
public function popFromHead()
{
if ($this->stack2->isEmpty()) {
if (!$this->stack1->isEmpty()) {
$value = $this->stack1->pop();
$this->stack2->push($value);
}
}
if ($this->stack2->isEmpty()) {
throw new Exception('Queue is empty.');
}
return $this->stack2->pop();
}
}
//测试代码
$queue = new StackQueue();
$queue->pushToTail(100);
$queue->pushToTail('PHP面试题');
$queue->pushToTail('学院君');
try {
while ($value = $queue->popFromHead()) {
var_dump($value);
}
} catch (Exception $exception) {
echo $exception->getMessage();
}
echo "\n";
exit();