PHP学习笔记:数据结构与算法
PHP学习笔记:数据结构与算法
概述:数据结构和算法是计算机科学中非常重要的两个概念,它们是解决问题和优化代码性能的关键。在PHP编程中,我们常常需要使用各种数据结构来存储和操作数据,同时也需要使用算法来实现各种功能。本文将介绍一些常用的数据结构和算法,并提供相应的PHP代码示例。
一、线性结构
- 创建数组:$arr = array(1, 2, 3);
- 添加元素:$arr[] = 4;
- 访问元素:$arr[0];
- 删除元素:unset($arr[0]);
- 数组长度:count($arr);
- 循环遍历:foreach ($arr as $value) { ... }
class Node { public $data; public $next; public function __construct($data = null) { $this->data = $data; $this->next = null; } } class LinkedList { public $head; public function __construct() { $this->head = null; } public function insert($data) { $newNode = new Node($data); if ($this->head === null) { $this->head = $newNode; } else { $currentNode = $this->head; while ($currentNode->next !== null) { $currentNode = $currentNode->next; } $currentNode->next = $newNode; } } public function display() { $currentNode = $this->head; while ($currentNode !== null) { echo $currentNode->data . " "; $currentNode = $currentNode->next; } } } $linkedList = new LinkedList(); $linkedList->insert(1); $linkedList->insert(2); $linkedList->insert(3); $linkedList->display();登录后复制
class Stack { private $arr; public function __construct() { $this->arr = array(); } public function push($data) { array_push($this->arr, $data); } public function pop() { if (!$this->isEmpty()) { return array_pop($this->arr); } } public function isEmpty() { return empty($this->arr); } } $stack = new Stack(); $stack->push(1); $stack->push(2); $stack->push(3); echo $stack->pop(); // 输出 3登录后复制