队列:先进先出,是一个应用很广泛的数据结构,不管是存储还是消息,还是待执行任务等等,生活以及软件中使用的栗子比比皆是。
不多说直接上代码,参考多家,觉得这个是最符合中心思想的。为了区分是否满队列,我们还是j决定使用空一格是满的,示意图如下
直接上代码
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
|
//循环队列,顺序存储
class
queue{
private
$data
;
private
$front
;
private
$rear
;
//定义最大容量
const
MAX=5;
//定义数量
//初始化队列,头指针和尾指针都只指向0,而且我们的满规定是空一个。
function
__construct(){
$this
->data=
array
();
$this
->front=0;
$this
->rear=0;
echo
"队列准备ok"
;
}
//一个有趣的小公式,因为我们规定中间间隔一个就是满了,原理和示意图用图片
public
function
queueLength(){
echo
(
$this
->rear-
$this
->front+self::MAX)%self::MAX;
}
//入队列
//没必要加入本队列参数,用$this
public
function
inQueue(
$e
){
if
((
$this
->rear+1)%(self::MAX)==
$this
->front){
echo
'队列已经满了'
;
die
;
}
$this
->data[
$this
->rear]=
$e
;
$this
->rear=(
$this
->rear+1)%(self::MAX);
echo
'ok'
;
}
public
function
deQueue(){
if
(
$this
->front==
$this
->rear){
echo
'队列是空的'
;
die
;
}
//var $tmp;
//$tmp =
$this
->data[
$this
->front]=
''
;
$this
->front = (
$this
->front+1)%self::MAX;
//unset($this->data[$this->front]);
echo
'ok'
;
}
}
|
测试代码如下:
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
|
$obj
=
new
queue();
$obj
->inQueue(1);
$obj
->inQueue(2);
var_dump(
$obj
);
$obj
->deQueue();
var_dump(
$obj
);
$obj
->inQueue(3);
var_dump(
$obj
);
$obj
->inQueue(4);
var_dump(
$obj
);
$obj
->inQueue(5);
var_dump(
$obj
);
$obj
->deQueue();
var_dump(
$obj
);
$obj
->deQueue();
var_dump(
$obj
);
$obj
->deQueue();
var_dump(
$obj
);
$obj
->deQueue();
var_dump(
$obj
);
$obj
->queueLength();
$obj
->inQueue(1);
var_dump(
$obj
);
$obj
->inQueue(2);
var_dump(
$obj
);
|
有一首小诗我觉得作者写的很好,增加点文学气息
谢谢,愿法界众生,皆得安乐
本文转自 jackdongting 51CTO博客,原文链接:http://blog.51cto.com/10725691/1949508