欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php如何实现链表?

程序员文章站 2022-03-07 12:35:42
...

php实现链表的方法:首先定义一个节点类,代码为【function __construct($val=null)】;然后实现链表的实现类,代码为【function_construct $this->dummyhead = new Nod】。

php如何实现链表?

php实现链表的方法:

首先定义一个节点类

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

链表的实现类

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--;
    }
}

相关学习推荐:PHP编程从入门到精通

以上就是php如何实现链表?的详细内容,更多请关注其它相关文章!

相关标签: php 链表