* A double-ended queue (deque, full name double-ended queue) is a data structure with queue and stack properties.
* Elements in a double-ended queue can be popped from both ends, and insertion and deletion operations are limited to both sides of the queue.
*/
class Deque
{
public $queue=array();
/**
* Constructor initializes the queue
*/
public function __construct($queue=array())
{
if(is_array($queue))
{
$this->queue=$queue;
}
}
/**
* Get the first element
*/
public function front()
{
return reset($this->queue);
}
/**
* Get the last element
*/
public function back()
{
return end($this->queue);
}
/**
* Determine whether it is empty
*/
public function is_empty()
{
return empty($this->queue);
}
/**
* Queue size
*/
public function size()
{
return count($this->queue);
}
/**
* Insert to end
*/
public function push_back($val)
{
array_push($this->queue,$val);
}
/**
*Insert to the end
*/
public function push_front($val)
{
array_unshift($this->queue,$val);
}
/**
* Remove the last element
*/
public function pop_back()
{
return array_pop($this->queue);
}
/**
* Remove the first element
*/
public function pop_front()
{
return array_shift($this->queue);
}
/**
* Clear the 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();
复制代码
PHP
Statement:
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