How to implement linked list in php?

coldplay.xixi
Release: 2023-03-02 10:50:01
Original
2495 people have browsed it

php method to implement a linked list: first define a node class, the code is [function __construct($val=null)]; then implement the implementation class of the linked list, the code is [function_construct $this->dummyhead = new Nod].

How to implement linked list in php?

php method to implement linked list:

First define a node class

class Node{
    public $val;
    public $next;
    function __construct($val=null){
        $this->val = $val;
        $this->next = null;
    }
}
Copy after login

Implementation class of linked list

class MyLinkedList {
    public $dummyhead; //定义一个虚拟的头结点
    public $size;
  
    function __construct() {
        $this->dummyhead = new Node(); 
        $this->size = 0;
    }
  
 
    function get($index) {
        if($index < 0 || $index >= $this->size)
            return -1;
        $cur = $this->dummyhead;
        for($i = 0; $i < $index; $i++){
            $cur = $cur->next;
        }
        return $cur->next->val;
    }
  
    function addAtHead($val) {
        $this->addAtIndex(0,$val);
    }
  
  
    function addAtTail($val) {
        $this->addAtIndex($this->size,$val);
    }
  
    function addAtIndex($index, $val) {
        if($index < 0 || $index > $this->size)
            return;
        $cur = $this->dummyhead;
        for($i = 0; $i < $index; $i++){
            $cur = $cur->next;
        }
        $node = new Node($val);
        $node->next = $cur->next;
        $cur->next = $node;
        $this->size++;
    }
  
    function deleteAtIndex($index) {
        if($index < 0 || $index >= $this->size)
            return;
        $cur = $this->dummyhead;
        for($i = 0; $i < $index; $i++){
            $cur = $cur->next;
        }
        $cur->next = $cur->next->next;
        $this->size--;
    }
}
Copy after login

Related learning recommendations:PHP programming from entry to proficiency

The above is the detailed content of How to implement linked list in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template