


A brief discussion on how to implement and process linked lists in PHP
This article will introduce to you how to implement and process linked lists in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
[Recommended learning: "PHP Video Tutorial"]
Linked List
A linked list is a non-continuous and non-sequential storage structure on a physical storage unit. The logical order of data elements is realized through the link order of pointers in the linked list. A linked list consists of a series of nodes (each element in the linked list is called a node), and nodes can be dynamically generated at runtime.
Forms: single linked list, double linked list, skip list (the redis collection data structure is realized by skip list, time complexity O (log N))
Learn about skip list: https://lotabout .me/2018/skip-list/
php implements the add, delete, modify and query operations on the linked list
Define node class:
<?php class Node { public $val; public $next; public function __construct( $val = null, $next = null ) { $this->val = $val; $this->next = $next; } }
Linked list class:
<?php /**链表 * Class Linklist * @package app\models */ class Linklist { public $head; //头节点(默认一个虚拟头节点) public $size; //长度 public function __construct() { $this->head = new Node(); $this->size = 0; } //头插法 public function addFirst( $value ){ // $node = new Node($value); // $node->next = $this->head; // $this->head = $node; //简化 // $this->head = new Node( $value, $this->head ); // $this->size++; $this->add(0,$value); } /**指定索引位置插入 * @param $index * @param $value * @throws Exception */ public function add( $index, $value ){ if( $index > $this->size ) throw new Exception('超过链表范围'); // if( $index==0 ){ // $this->addFirst($value); // }else{ $prev = $this->head; for($i=0;$inext; } // $node = new Node($value); // $node->next = $prev->next; // $prev->next = $node; $prev->next = new Node($value,$prev->next); // } $this->size++; } /**尾插法 * @param $value */ public function addLast( $value ){ $this->add($this->size,$value); } /*** * 编辑 * @param $index * @param $value * @throws Exception */ public function edit( $index, $value ){ if( $index > $this->size-1 ) throw new Exception('超过链表范围'); $prev = $this->head->next; for($i=0;$ival = $value; $prev = $prev->next; } } /** * 查询 * @param $index * @return null * @throws Exception */ public function select($index){ if( $index > $this->size-1 ) throw new Exception('超过链表范围'); $prev = $this->head->next; for($i=0;$inext; } } /**删除 * @param $index * @throws Exceptionr */ public function delete( $index ){ if( $index > $this->size-1 ) throw new Exception('超过链表范围'); $prev = $this->head; for($i=0;$inext = $prev->next->next; $prev = $prev->next; } $this->size--; } /**检索值是否存在 * @param $value * @return bool */ public function iscontain( $value ){ $prev = $this->head->next; while( $prev ){ if( $prev->val==$value ){ return true; } $prev = $prev->next; } return false; } /**转换为字符串 * @return string */ public function tostring(){ $prev = $this->head->next; $r = []; while( $prev ){ $r[] = $prev->val; $prev = $prev->next; } return implode('->',$r); } /** * 删除指定的节点值 * @param $value */ public function removeFileds( $value ){ $prev = $this->head; while( $prev->next ){ if( $prev->val == $value ){ $prev->val = $prev->next->val; $prev->next = $prev->next->next; }else{ $prev = $prev->next; } } } /** * 通过递归方式删除指定的节点值 * @param $value */ public function removeFiledsByRecursion( $value ){ $this->head = $this->removeByRecursion( $this->head ,$value); return $this->head; } public function removeByRecursion( $node , $value, $level=0 ){ if( $node->next == null ){ $this->showDeeep($level,$node->val); return $node->val == $value ? $node->next:$node; } $this->showDeeep($level,$node->val); $node->next = $this->removeByRecursion( $node->next,$value,++$level ); $this->showDeeep($level,$node->val); return $node->val == $value ? $node->next:$node; } /** * 显示深度 * 帮助理解递归执行过程,回调函数执行层序遵循系统栈 * @param int $level 深度层级 * @param $val * @return bool */ public function showDeeep( $level=1,$val ){ if( $level<p>The calling operation is as follows: </p><pre class="brush:php;toolbar:false"><?php $node = new Linklist(); $node->addFirst(1); $node->add(1,7); $node->add(2,10); $node->edit(1,8); var_dump($node->select(1)) ; $node->delete(1); $node->addLast(99); var_dump($node->iscontain(2)); var_export($node); var_export($node->tostring());
Analyze the time complexity of the linked list operation:
增: O(n) 只对链表头操作:O(1) 删: O(n) 只对链表头操作:O(1) 改:O(n) 查:O(n) 只对链表头操作:O(1)
Use the linked list to implement the stack
<?php /** * 链表实现栈 * Class LinklistStack * @package app\models */ class LinklistStack extends Linklist { /** * @param $value */ public function push( $value ){ $this->addFirst($value); } /** * @return mixed */ public function pop(){ $r = $this->head->next->val; $this->delete(0); return $r; } }
<?php $stack = new LinklistStack(); $stack->push(1); $stack->push(3); $stack->push(6); $stack->push(9); print_r($stack->pop()); print_r($stack->head);
Linked list implementation queue
<?php /** * 链表实现队列 * Class LinkListQueue * @package app\models */ class LinkListQueue extends Linklist { public $tail; //尾节点 /** * push * @param $value */ public function push( $value ){ if( $this->head->val==null ){ $this->tail = new Node( $value ); $this->head = $this->tail; }else{ $this->tail->next = new Node( $value ); $this->tail = $this->tail->next; } $this->size++; } /** * pop * @return null * @throws \Exception */ public function pop(){ if( $this->sizehead->val; $this->head = $this->head->next; $this->size--; return $val; } /** * 查看队首 */ public function checkHead(){ return $this->head->val; } /** * 查看队尾 */ public function checkEnd(){ return $this->tail->val; } /** * toString */ public function toString(){ $r = []; while( $this->head ){ $r[] = $this->head->val; $this->head = $this->head->next; } return implode('->',$r); } }
Test
<?php $stack = new LinkListQueue(); $stack->push(1); $stack->push(3); $stack->push(6); $stack->push(9); print_r($stack->pop()); print_r($stack->head); print_r($stack->checkHead()); print_r($stack->checkEnd()); print_r($stack->toString()); /** 1 app\models\Node Object ( [val] => 3 [next] => app\models\Node Object ( [val] => 6 [next] => app\models\Node Object ( [val] => 9 [next] => ) ) ) 3 9 3->6->9 **/
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of A brief discussion on how to implement and process linked lists in PHP. For more information, please follow other related articles on the PHP Chinese website!

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.