PHP简单双向队列实现
这是一个简单的PHP双向队列的实现:
<?phpclass Deque{public $queue = array();/*** 尾部入对* @param [type] $value [description]*/public function addLast($value){return array_push($this->queue,$value);}/*** 尾部出队* @return [type] [description]*/public function removeLast(){return array_pop($this->queue);}/*** 头部入队* @param [type] $value [description]*/public function addFirst($value){return array_unshift($this->queue, $value);}/*** 头部出队* @return [type] [description]*/public function removeFirst(){return array_shift($this->queue);}/*** 清空队列* @return [type] [description]*/public function makeEmpty(){unset($this->queue);}/*** 获取列头* @return [type] [description]*/public function getFirst(){return reset($this->queue);}/*** 获取列尾* @return [type] [description]*/public function getLast(){return end($this->queue);}/*** 获取长度* @return [type] [description]*/public function getLength(){return count($this->queue);}}
下面是队列的调用方式:
<?phprequire_once(‘testQueue.php’);$queue = new Deque();$queue->addLast(‘1’);$queue->addLast(‘2’);$queue->addLast(‘3’);print_r(‘队列中的元素:’.json_encode($queue->queue));$queue->addLast(‘4’);print_r(‘尾部入队:’.json_encode($queue->queue));$queue->removeLast();print_r(‘尾部出队:’.json_encode($queue->queue));$queue->addFirst(‘0’);print_r(‘头部入队:’.json_encode($queue->queue));$queue->removeFirst();print_r(‘头部出队:’.json_encode($queue->queue));print_r(‘获取列头:’.json_encode($queue->getFirst()));print_r(‘获取列尾:’.json_encode($queue->getLast()));print_r(‘获取长度:’.json_encode($queue->getLength()));$queue->makeEmpty();print_r(‘清空队列:’.json_encode(isset($queue->queue)));
来源:http://blog.csdn.net/kameleon2013/article/details/51527483