<?php /** * PHP實現(xiàn)雙向隊列,雙端隊列 * 雙端隊列(deque,全名double-ended queue)是一種具有隊列和棧性質(zhì)的數(shù)據(jù)結(jié)構(gòu)。 * 雙端隊列中的元素可以從兩端彈出,插入和刪除操作限定在隊列的兩邊進(jìn)行。 */ class Deque { public $queue=array(); /** * 構(gòu)造函數(shù)初始化隊列 */ public function __construct($queue=array()) { if(is_array($queue)) { $this->queue=$queue; } } /** * 獲取第一個元素 */ public function front() { return reset($this->queue); } /** * 獲取最后一個元素 */ public function back() { return end($this->queue); } /** * 判斷是否為空 */ public function is_empty() { return empty($this->queue); } /** * 隊列大小 */ public function size() { return count($this->queue); } /** * 插入到尾 */ public function push_back($val) { array_push($this->queue,$val); } /** * 插入到頭 */ public function push_front($val) { array_unshift($this->queue,$val); } /** * 移除最后一個元素 */ public function pop_back() { return array_pop($this->queue); } /** * 移除第一個元素 */ public function pop_front() { return array_shift($this->queue); } /** * 清空隊列 */ public function clear() { $this->queue=array(); } } //初始化一個雙向隊列 $deque=new Deque(array(1,2,3,4,5)); echo $deque->size().PHP_EOL; echo $deque->is_empty().PHP_EOL; echo $deque->front().PHP_EOL; echo $deque->back().PHP_EOL; echo PHP_EOL; //彈出元素測試 echo $deque->pop_back().PHP_EOL; echo $deque->pop_front().PHP_EOL; echo $deque->size().PHP_EOL; echo PHP_EOL; $deque->push_back('a').PHP_EOL; $deque->push_front(0).PHP_EOL; echo PHP_EOL; //插入測試 echo $deque->front().PHP_EOL; echo $deque->back().PHP_EOL; echo $deque->size().PHP_EOL; echo PHP_EOL; //清空測試 $deque->clear(); echo $deque->is_empty();
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article
How to fix KB5060533 fails to install in Windows 10?
4 weeks ago
By DDD
Dune: Awakening - Where To Get Insulated Fabric
3 weeks ago
By Jack chen
Gmail Login: How to Sign Up, Sign In, or Sign Out of Gmail - MiniTool
1 months ago
By Jack chen
How to fix KB5060999 fails to install in Windows 11?
3 weeks ago
By DDD
Guild Guide In Tainted Grail: The Fall Of Avalon
4 weeks ago
By Jack chen

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
