PHP算法學習(6) 單向鏈表 實現棧

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

 這個是模擬棧的先進後出的一個鏈表操做,自動維護鏈表,固然你也使用SPL的棧node

測試版本php 5.4 ,5.6,7.0,7.2git

/*
 * 鏈表測試到輔助類
 */

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);
相關文章
相關標籤/搜索