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);
  • 相关阅读:
    python学习第十五天
    python学习第十三、十四天
    python学习第十二天
    python学习第j十一天
    python学习第十天
    ViewController push的自定义动画
    iOS 判断设备是否越狱
    iOS
    OBJC字面量
    ios8 share Extension 分享扩展
  • 原文地址:https://www.cnblogs.com/zx-admin/p/10373866.html
Copyright © 2011-2022 走看看