php实现数据结构
PHP 实现常见数据结构的方法
PHP 作为一门灵活的脚本语言,可以通过数组、类和 SPL(标准 PHP 库)实现多种数据结构。以下是几种常见数据结构的实现方式:
数组实现栈(LIFO)
PHP 数组原生支持栈操作,使用 array_push() 和 array_pop() 即可:
$stack = [];
array_push($stack, 'a'); // 入栈
$top = array_pop($stack); // 出栈
类实现队列(FIFO)
通过类封装数组实现先进先出队列:
class SimpleQueue {
private $queue = [];
public function enqueue($item) {
array_push($this->queue, $item);
}
public function dequeue() {
return array_shift($this->queue);
}
}
SPL 双向链表
PHP 的 SPL 库提供 SplDoublyLinkedList:
$list = new SplDoublyLinkedList();
$list->push('a'); // 尾部添加
$list->unshift('b'); // 头部添加
$list->pop(); // 尾部移除
哈希表实现
PHP 的关联数组本身就是哈希表的实现:
$hashMap = [];
$hashMap['key'] = 'value'; // 插入
$value = $hashMap['key'] ?? null; // 查找
二叉搜索树
通过类实现二叉树节点和基本操作:
class TreeNode {
public $data;
public $left = null;
public $right = null;
public function __construct($data) {
$this->data = $data;
}
}
// 插入示例
function insert($root, $data) {
if ($root === null) return new TreeNode($data);
if ($data < $root->data) {
$root->left = insert($root->left, $data);
} else {
$root->right = insert($root->right, $data);
}
return $root;
}
优先队列
SPL 提供 SplPriorityQueue:
$pq = new SplPriorityQueue();
$pq->insert('task1', 3);
$pq->insert('task2', 1);
$pq->extract(); // 返回优先级最高的'task1'
图结构
通过邻接表实现图:

class Graph {
private $adjList = [];
public function addEdge($src, $dest) {
$this->adjList[$src][] = $dest;
$this->adjList[$dest][] = $src; // 无向图需双向添加
}
}
性能注意事项
- 数组成员操作:
array_shift()时间复杂度为 O(n),不适合大规模队列 - SPL 数据结构经过优化,适合处理大量数据
- 复杂结构(如红黑树)建议使用第三方库如 PHPDS
以上实现方式可根据实际需求选择原生数组、类封装或 SPL 库,平衡开发效率与运行时性能。






