PHP实现-一个双向队列

2018-08-22 14:17 By "Powerless" 2968 0 1

单向队列:只能从头进,从尾出

$array =  array('PHP', 'JAVA');
array_push($array, 'PYTHON'); //入队列
array_shift($array); //出队列


双向队列:头尾都可以进出

class Deque{
    private $queue=array();
    function addFirst($item){//头入队
        return array_unshift($this->queue,$item);
    }
    function addLast($item){//尾入队
        return array_push($this->queue,$item);
    }
    function removeFirst(){//头出队
        return array_shift($this->queue);
    }
    function removeLast(){//尾出队
        return array_pop($this->queue);
    }
    function show(){//显示
        echo implode(" ",$this->queue);
    }
    function clear(){//清空
        unset($this->queue);
    }
    function getFirst(){
        return array_shift($this->queue);
    }
    function getLast(){
        return array_pop($this->queue);
    }
    function getLength(){
        return count($this->queue);
    }
}
$q=new Deque();
$q->addFirst(1);
$q->addLast(5);
$q->removeFirst();
$q->removeLast();
$q->addFirst(2);
$q->addLast(4);
$q->show();


评 论

View in WeChat

Others Discussion

  • 初识七层、五层、四层网络协议
    Posted on 2021-04-09 16:52
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP扩展安装
    Posted on 2019-06-24 11:28
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • ACID原则
    Posted on 2020-12-17 16:36
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • MySQL分组
    Posted on 2019-11-18 14:00