栈与队列
栈是限定仅在表尾进行插入和删除操作的线性表
队列是只允许在一端进行插入操作,而在另一端进行删除操作的线性表
栈
我们把允许插入和删除的一端称为栈顶(top),另一端称为栈底(bottom),不含任何数据元素的栈称为空栈。栈又称为后进先出的线性表,简称LIFO结构
栈的顺序存储结构及实现
<?php
namespace App\Http\Models\Stack;
/**
* 顺序存储
* 栈
*/
class ArrayStack {
private $data = [];
private $top = 0; //栈顶指针
private $len = 0; //栈大小
function __construct($len, $data = [])
{
$this->len = $len;
$this->data = $data;
$this->top = count($data) - 1;
}
/**
* 入栈操作
*/
function push($value) {
if ($this->checkLen() == false) {
return '栈满了';
}
$this->top++;
$this->data[$this->top] = $value;
return true;
}
/**
* 出栈操作
*/
function pop() {
if ($this->isEmpty()) {
return '空栈';
}
$index = $this->top;
$this->top--;
return $this->data[$index];
}
function isEmpty() {
if ($this->top == -1) {
return true;
}
return false;
}
private function checkLen() {
if ($this->top >= $this->len - 1) {
return false;
}
return true;
}
function list() {
return $this->data;
}
}
栈的链式存储结构及实现
<?php
namespace App\Http\Models\Stack;
use App\Http\Models\LinkList\Node;
/**
* 链式存储
* 栈
* 链栈
*/
class LinkTable {
private $top; //栈顶指针
private $len = 0; //栈大小
function __construct()
{
$this->head = new Node();
}
/**
* 在链栈添加元素
*/
function push($data) {
$node = new Node($data);
$node->next = $this->top; //把原来的栈顶元素放到新元素的下面
$this->top = $node; //把栈顶指向新元素
$this->len++;
}
function isEmpty() {
if ($this->len == 0) {
return true;
}
return false;
}
/**
* 删除线性表指定位置的元素
*/
function pop() {
if ($this->isEmpty()) {
return '空栈';
}
$elem = $this->top; //把要弹出的栈顶返回
$this->top = $this->top->next; //把栈顶指向原来栈顶的下一个元素
$this->len--;
return $elem;
}
}
队列
队列链表的实现
<?php
namespace App\Http\Models\Queue;
use App\Http\Models\LinkList\Node;
/**
* 链式存储
* 队列
* 链队列
*/
class LinkQueue {
private $front; //对头指针
private $rear; //对尾指针
private $len = 0; //队列大小
function __construct()
{
$node = new Node();
$this->front = &$node;
$this->rear = &$node;
}
/**
* 在链队列添加元素
*/
function push($data) {
$node = new Node($data);
$this->rear->next = $node; //把新元素放到队列尾的后面
$this->rear = $node; //把队列尾指向新元素
$this->len++;
}
function isEmpty() {
if ($this->len == 0) {
return true;
}
return false;
}
/**
* 在链队列弹出元素
*/
function pop() {
if ($this->isEmpty()) {
return '空队列';
}
$elem = $this->front->next; //把要弹出的队列头返回
$this->front->next = $elem->next; //把队列头指向原来队列头的下一个元素
$this->len--;
return $elem;
}
}