zoukankan      html  css  js  c++  java
  • PHP算法学习(6) 单向链表 实现栈

    svn地址:svn://gitee.com/zxadmin/live_z 

     这个是模拟栈的先进后出的一个链表操作,自动维护链表,当然你也使用SPL的栈

    测试版本php 5.4 ,5.6,7.0,7.2

    /*
     * 链表测试到辅助类
     */
    
    final class Node {
    
        public $data;
        public $next = null;
    
        public function __construct($data) {
            $this->data = $data;
        }
    
    }
    <?php
    
    /*
     * 单向链表,注意是使用数组模拟单链表到特性,也可以理解为有单向链接到数组
     */
    
    final class SinglyLinkedList {
    
        protected $list = null;
    
    //    //从链表尾部压入一个节点,节点自动维护,不需要要像main方法那样自己维护
        public function push(Node $head, Node $Node) {
            $current = $head; //让$current指向$head;
            while ($current->next != null) {
                $current = $current->next;
            }
            $current->next = $Node->next;
            $current->next = $Node;
        }
    
        //从链表尾压出一个节点
        public function pop(Node $head) {
            $current = $head; //让$current指向$head;
            while ($current->next != null) {
                //提前查找链表尾部是否为空,为空就是尾部,吧当前节点的next复制问NULL,就是尾部元素干掉
                if ($current->next->next == null) {
                    break;
                }
                $current = $current->next;
            }
            $current->next = null;
        }
    
        //非自动维护一个链表,只是单纯点组成一个链表
        public static function main() {
            $header = new Node(null);
    
            $node1 = new Node(['id' => 2, 'name' => '李1']);
            $header->next = $node1;
    
            $node2 = new Node(['id' => 5, 'name' => '李5']);
            $node1->next = $node2;
    
            $node3 = new Node(['id' => 7, 'name' => '李7']);
    
            $node2->next = $node3;
            pp($header);
    
            self::getAllNode($header);
        }
    
        public static function getAllNode($header) {
            $cur = $header;
            while ($cur->next != null) {
                $cur = $cur->next;
                p($cur->data);
            }
        }
    
    }

    测试

    //单链表
    $head = new Node([]);
    
    $SinglyLinkedList = new SinglyLinkedList();
    $node1 = new Node(['id' => 2, 'name' => '李1']);
    $SinglyLinkedList->push($head, $node1);
    
    //pp($SinglyLinkedList->getList());
    $node2 = new Node(['id' => 5, 'name' => '李5']);
    $SinglyLinkedList->push($head, $node2);
    
    $node3 = new Node(['id' => 7, 'name' => '李7']);
    $SinglyLinkedList->push($head, $node3);
    
    $SinglyLinkedList->pop($head);
    pp($head);
  • 相关阅读:
    文件夹选项查看显示所有文件和文件夹..确定后隐藏文件依然不能显示,.
    加速电脑启动,给电脑瘦身
    进行性肌营养不良症的治疗
    可变量程的直流电压表
    数字图象处理课件 下载
    两顾高楼
    技巧心得:给拥有Google AdSense 帐户 朋友的一点忠告
    进行性肌营养不良研究又有新的发现
    电子通讯系统 >> BAS系统在地铁环境控制中的应用及实现
    J2ME游戏开发中时钟的简单实现
  • 原文地址:https://www.cnblogs.com/zx-admin/p/10373866.html
Copyright © 2011-2022 走看看