1. 程式人生 > >PHP算法學習(7) 雙向鏈表 實現棧

PHP算法學習(7) 雙向鏈表 實現棧

代碼 != pda 算法 互相連接 不能 UNC 需要 break

2019年2月25日17:24:34

final class BasicNode {

    public $index;
    public $data;
    public $next = null;
    public $pre = null;

    public function __construct($index, $data) {
        $this->index = $index;
        $this->data = $data;
    }

}
<?php

/*
 * 雙向鏈表
 
*/ final class DoublyLinkedList { //從鏈表尾部壓入一個節點,節點自動維護,不需要要像main方法那樣自己維護 public function add(BasicNode $head, BasicNode $Node) { $current = $head; //讓$current指向$head; //順序聯表根據index排序 while ($current->next != null) { //head元素為空,從第一個有數據元素開始檢測 if
($current->next->index > $Node->index) {//如果有相同的index就不能插入 break; //$current沒有 next元素 } elseif ($current->next->index == $Node->index) { throw new \Exception(‘index重復‘); } $current = $current->next
; } // p($current); //沒有元素,和尾部插入元素 //中間插入情況 if ($current->next != null) { $Node->next = $current->next; } $Node->pre = $current; if ($current->next != null) { $current->next->pre = $Node; } $current->next = $Node; } //從鏈表尾壓出一個節點 public function delete(BasicNode $head, $index) { $current = $head; //讓$current指向$head; $has = false; while ($current->next != null) { //提前查找鏈表尾部是否為空,為空就是尾部,吧當前節點的next復制問NULL,就是尾部元素幹掉 if ($current->next->index == $index) { $has = true; break; } $current = $current->next; } if (!$has) { throw new \Exception(‘index沒有找到‘); } if ($current->next != null) { $current->next->pre = $current; } $current->next = $current->next->next; } //修改數據 public function update(BasicNode $head, $index, $data) { $current = $head; //讓$current指向$head; $has = false; while ($current->next != null) { if ($current->next->index == $index) { $has = true; break; } $current = $current->next; } if (!$has) { throw new \Exception(‘index沒有找到‘); } $current->next->data = $data; } }

測試代碼

$head = new BasicNode(null, []);
$a = new BasicNode(1, [‘a‘]);
$b = new BasicNode(5, [‘b‘]);
$c = new BasicNode(8, [‘c‘]);
$d = new BasicNode(99, [‘d‘]);
$e = new BasicNode(66, [‘e‘]);

//if ($head->next->index > 1) {
//    pp(‘大於‘);
//} else {
//    pp(‘小於‘);
//}

$DoublyLinkedList = new DoublyLinkedList();
$DoublyLinkedList->add($head, $b);
//pp($head);
$DoublyLinkedList->add($head, $a);
//pp($head);
$DoublyLinkedList->add($head, $d);
$DoublyLinkedList->add($head, $e);

$DoublyLinkedList->add($head, $c);

//$DoublyLinkedList->update($head, 5, [‘2312321‘]);
$DoublyLinkedList->delete($head, 99);
pp($head);

最麻煩的是新增的時候去維護互相連接的中間節點

PHP算法學習(7) 雙向鏈表 實現棧