Home > php教程 > php手册 > How to implement a singly linked list during the development process of python (code)

How to implement a singly linked list during the development process of python (code)

坏嘻嘻
Release: 2018-09-15 09:33:11
Original
10641 people have browsed it

This article introduces how to implement a singly linked list. I hope you will learn patiently.         

//节点class node{
    //初始化变量,包括存储的内容 和 下一个数据的指针
    public $id = 0;    public $data = '';    public $next = null;    //构造函数,设置存储内容的数据
    public function __construct($id, $data)
    {
        $this->id = $id;    
            $this->data = $data;
    }
}//单链表 
  class singelLinkList{
    private $header;
     //链表头节点   
    //添加节点数据   
    public function addLink($id = null, $name = null)
    {
        $node = new node ($id, $name);     
           $current = $this->header;    
               if (!$current) {       
                    $this->header = $node;
             } else {       
                  # 链表头插
             $node->next = $current;   
                       $this->header = $node;  
                                 # 链表尾插
            /*# 循环,获取对象中最后一个元素
            while ($current->next != null) {
                $current = $current->next;
            }
            # 最后一个元素的next指针指向$node
            $current->next = $node;*/
        }
    }    public function delLink($id = null, $name = null)
    {
        $current = $this->header;        # 循环
        while ($current->next != null) {        
            # 查找待删除元素 $delCurrent 的上一个元素
            if ($current->next->id == $id) {         
                   $delCurrent = $current->next;         
                          # 查找待删除元素 $delCurrent 的下一个元素
                $current->next = $delCurrent->next;        
                        # 删除元素 $delCurrent
                $delCurrent = null;      
                          break;
            }         
               $current = $current->next;
        }

    }
}$lists = new singelLinkList();
$lists->addLink(1, 'aaaaaa');
$lists->addLink(2, 'bbbbbb');
$lists->addLink(3, 'cccccc');
$lists->addLink(4, 'dddddd');
$lists->addLink(5, 'eeeeee');
$lists->delLink(4);echo &#39;<pre class="brush:php;toolbar:false">&#39;; 
print_r($lists);
Copy after login

The above is the detailed content of How to implement a singly linked list during the development process of python (code). 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template