Repository navigation
Expand file tree
/
Copy pathLinkedListQueue.php
More file actions
111 lines (101 loc) · 2.53 KB
/
Copy pathLinkedListQueue.php
File metadata and controls
111 lines (101 loc) · 2.53 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<?php
namespace Datastruct;
require_once("./autoload.php");
use Datastruct\QueueInterface;
use Datastruct\Node;
/**
* 链表队列
* Class LinkedListQueue
* @package Datastruct
*/
class LinkedListQueue implements QueueInterface
{
private $head;//队列头节点
private $tail;//队列尾节点
private $size;//队列长度
public function __construct()
{
$this->head = null;
$this->tail = null;
$this->size = 0;
}
/**
* 入队
* @param Node $ele
* @return bool
*/
public function enqueue($ele)
{
//如果尾节点为空
if ($this->tail == null) {
$this->tail = new Node($ele);
$this->head = $this->tail;
} else {
//初始化新节点,tail的next指向新节点, 然后设置tail为新节点
$this->tail->next = new Node($ele);
$this->tail = $this->tail->next;
}
$this->size++;
return true;
}
/**
* 出队
* @return mixed
*/
public function dequeue()
{
if ($this->head == null) {
throw new \RuntimeException('链表为空,无法出队');
}
$delNode = $this->head;
//将头节点指向下一个节点
$this->head = $this->head->next;
//如果重新指向后的头节点为空,则队列为空
if ($this->head == null) {
$this->tail = null;
}
$this->size --;
return $delNode->data;
}
/**
* 查看链表队列队首元素
*/
public function getFirst()
{
if ($this->isEmpty()) {
throw new \RuntimeException('队列为空');
}
return $this->head->data;
}
/**
* 获取链表队列长度
* @return int
*/
public function getSize(): int
{
return $this->size;
}
/**
* 判断链表队列是否为空
* @return bool
*/
public function isEmpty(): bool
{
return $this->size == 0;
}
/**
* 打印数组时的格式
* @return string
*/
public function __toString():string
{
$str = sprintf("LinkedQueue Size: %d\n(\nHead", $this->getSize(), $this->getSize());
$curNode = $this->head;
while ($curNode != null) {
$str .= ' ' . $curNode->data . ' -> ';
$curNode = $curNode->next;
}
$str .= "\n)";
return $str;
}
}