PHP算法学习(6) 单向链表 实现栈
生活随笔
收集整理的這篇文章主要介紹了
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);?
轉載于:https://www.cnblogs.com/zx-admin/p/10373866.html
總結
以上是生活随笔為你收集整理的PHP算法学习(6) 单向链表 实现栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解谜游戏《IB 恐怖美术馆》eShop
- 下一篇: [PHP] MIME邮件协议的multi