利用鏈表實現棧和隊列 php

棧: http://data.biancheng.net/view/169.html
隊列: http://data.biancheng.net/view/172.html

php鏈表類: https://blog.csdn.net/Gekkoou/article/details/105127971

use LinkedList;

class LinkedListStack extends LinkedList{

    //入棧
    public function push($data){
        $this->addHead($data);
    }

    //出棧
    public function pop(){
        if($this->size == 0)
            throw new \Exception('stack is empty');

        $data = $this->head->data;
        $this->delHead();
        return $data;
    }
}

#測試
echo '<pre>';
$node = new LinkedListStack();
$node->push(2);
$node->push(3);
$node->push(4);
$node->pop();
print_r($node);

隊列

use LinkedList;

class LinkedListQueue extends LinkedList{

    //入隊
    public function push($data){
        $this->addTail($data);
    }

    //出隊
    public function pop(){
        if($this->size == 0)
            throw new \Exception('queue is empty');

        $data = $this->head->data;
        $this->delHead();
        return $data;
    }
}

#測試
echo '<pre>';
$node = new LinkedListQueue();
$node->push(2);
$node->push(3);
$node->push(4);
$node->pop();
print_r($node);





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章