网络语言系列&php系列【仅供参考】:PHP实现双向队列

PHP实现双向队列




PHP实现双向队列

在 PHP 中,虽然标准库没有直接提供一个双向队列(Deque)的实现,但我们可以使用 SplDoublyLinkedList 类来实现这一功能。SplDoublyLinkedList 是一个双向链表,它允许我们在列表的头部和尾部进行插入和删除操作,这符合双向队列的基本特性。

下面是一个使用 SplDoublyLinkedList 实现双向队列的示例代码:

<?php
 
class Deque {
    private $deque;
 
    public function __construct() {
        $this->deque = new SplDoublyLinkedList();
    }
 
    // 在队列尾部添加元素
    public function enqueue($value) {
        $this->deque->push($value);
    }
 
    // 在队列头部添加元素(也可以看作是在队列的另一端添加)
    public function enqueueFront($value) {
        $this->deque->unshift($value);
    }
 
    // 从队列尾部移除元素
    public function dequeue() {
        if ($this->isEmpty()) {
            throw new UnderflowException("Deque is empty, cannot dequeue.");
        }
        return $this->deque->pop();
    }
 
    // 从队列头部移除元素(也可以看作是在队列的另一端移除)
    public function dequeueFront() {
        if ($this->isEmpty()) {
            throw new UnderflowException("Deque is empty, cannot dequeue from front.");
        }
        return $this->deque->shift();
    }
 
    // 获取队列头部的元素(不移除)
    public function peek() {
        if ($this->isEmpty()) {
            throw new UnderflowException("Deque is empty, cannot peek.");
        }
        return $this->deque->bottom();
    }
 
    // 获取队列尾部的元素(不移除)
    public function peekEnd() {
        if ($this->isEmpty()) {
            throw new UnderflowException("Deque is empty, cannot peek at end.");
        }
        return $this->deque->top();
    }
 
    // 检查队列是否为空
    public function isEmpty() {
        return $this->deque->isEmpty();
    }
 
    // 获取队列中的元素数量
    public function count() {
        return $this->deque->count();
    }
 
    // 打印队列中的元素(用于调试)
    public function printDeque() {
        echo implode(' <-> ', $this->deque->toArray()) . "\n";
    }
}
 
// 示例用法
$deque = new Deque();
$deque->enqueue(1);
$deque->enqueue(2);
$deque->enqueueFront(0);
$deque->printDeque(); // 输出: 0 <-> 1 <-> 2
echo "Peek: " . $deque->peek() . "\n"; // 输出: Peek: 1
echo "Dequeue: " . $deque->dequeue() . "\n"; // 输出: Dequeue: 1
$deque->printDeque(); // 输出: 0 <-> 2
echo "Peek end: " . $deque->peekEnd() . "\n"; // 输出: Peek end: 2
echo "Dequeue front: " . $deque->dequeueFront() . "\n"; // 输出: Dequeue front: 0
$deque->printDeque(); // 输出: 2
?>

在这个示例中,Deque 类封装了一个 SplDoublyLinkedList 实例,并提供了标准的双向队列操作,如 enqueue(在尾部添加)、enqueueFront(在头部添加)、dequeue(从尾部移除)、dequeueFront(从头部移除)、peek(查看头部元素)、peekEnd(查看尾部元素)、isEmpty(检查是否为空)和 count(获取元素数量)。此外,还有一个 printDeque 方法用于打印队列中的元素,便于调试。

请注意,SplDoublyLinkedList 的 push 方法在尾部添加元素,unshift 方法在头部添加元素,pop 方法从尾部移除元素,而 shift 方法从头部移除元素。这些操作使得 SplDoublyLinkedList 非常适合用作双向队列的底层实现。







ac-er8888

PHP实现双向队列

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坦笑&&life

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值