利用链表实现栈和队列 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);





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