队列
- 队列是典型的 FIFO 数据结构。插入(insert)操作也称作入队(enqueue),新元素始终被添加在队列的末尾。 删除(delete)操作也被称为出队(dequeue)。 你只能移除第一个元素
- 先入先出
class Queue
{
private $queue;
private $size = 0; //队列长度
private $k = 0; //队列个数
public function __construct(int $k)
{
$this->queue = [];
$this->size = 0;
$this->k = $k;
}
/**
* 入队
* @param $data
* @return Queue|null
*/
public function enQueue($data): ?Queue
{
if ($this->size <= $this->k) {
$this->queue[$this->size] = $data;
$this->size++;
return $this;
}
return null;
}
/**
* 获取队列
* @return array
*/
public function getQueue(): array
{
if (empty($this->queue)) {
return [-1];
}
return $this->queue;
}
/**
* 获取队列大小
* @return int
*/
public function getSize(): int
{
return $this->size;
}
/**
* 出队
*/
public function deQueue()
{
if (empty($this->queue)) {
return [-1];
}
unset($this->queue[0]);
return $this->queue[0];
}
/**
* 检查循环队列是否为空
*/
public function isEmpty(): bool
{
if (empty($this->queue)) {
return true;
}
return false;
}
/**
* 检查循环队列是否已满
* @return bool
*/
public function isFull(): bool
{
if ($this->size > $this->k) {
return true;
}
return false;
}
}
$queue = new Queue(3);
//入队
$queue ->enQueue(1)->enQueue(2)->enQueue(3)->enQueue(33);
//出队
$queue->deQueue();
echo '<pre>' , print_r( $queue ->getQueue(), TRUE), '</pre>' ;
//获取队列大小
//echo $queue->getSize();
//检测队列是否已满
//print_r($queue->isFull());
栈
- 后入先出
- 栈和队列不同,栈一个LIFO数据结构,插入操作在栈中被称为入栈push,与队列类似总是在堆栈的末尾添加一个
- 新元素,但是删除操作退栈。始终删除队列中先对于它的最后一个元素
class Stack
{
private $stackArray = [];
private $stackMax = 10; // 栈顶最大值(用于控制栈长度,是否栈满)
private $top = -1;
private $out;
/**
* 入栈
* @param string $value
* @return string
*/
public function pushStack($value = ''): string
{
if (empty($value)) return '压入的栈的值不能为空';
if ($this->top == $this->stackMax) {
return '栈已经满了!';
}
array_push($this->stackArray, $value);
++$this->top;
return $this->top;
}
/**
* 出栈
*/
public function popValue(): string
{
if ($this->top == -1)
return '栈内没有数据';
$this->out = array_pop($this->stackArray);
--$this->top;
return '出栈成功,当前栈顶值:' . $this->top . '出栈值:' . $this->out;
}
/**
* 获取栈内信息
*/
public function getSatck(): array
{
return $this->stackArray;
}
public function __destruct()
{
echo 'over ';
}
}
$r = new Stack();
//入栈
$r->pushStack('t');
$r->pushStack('b');
$r->pushStack('n');
//出栈
$r->popValue();
//获取栈
print_r($r->getSatck());