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

2019年2月25日17:24:34php

 

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);

 

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

相關文章
相關標籤/搜索