File indexing completed on 2024-04-28 05:58:54

0001 <?php
0002 
0003 /**
0004  * A simple array-backed queue, based off of the classic Okasaki
0005  * persistent amortized queue.  The basic idea is to maintain two
0006  * stacks: an input stack and an output stack.  When the output
0007  * stack runs out, reverse the input stack and use it as the output
0008  * stack.
0009  *
0010  * We don't use the SPL implementation because it's only supported
0011  * on PHP 5.3 and later.
0012  *
0013  * Exercise: Prove that push/pop on this queue take amortized O(1) time.
0014  *
0015  * Exercise: Extend this queue to be a deque, while preserving amortized
0016  * O(1) time.  Some care must be taken on rebalancing to avoid quadratic
0017  * behaviour caused by repeatedly shuffling data from the input stack
0018  * to the output stack and back.
0019  */
0020 class HTMLPurifier_Queue {
0021     private $input;
0022     private $output;
0023 
0024     public function __construct($input = array()) {
0025         $this->input = $input;
0026         $this->output = array();
0027     }
0028 
0029     /**
0030      * Shifts an element off the front of the queue.
0031      */
0032     public function shift() {
0033         if (empty($this->output)) {
0034             $this->output = array_reverse($this->input);
0035             $this->input = array();
0036         }
0037         if (empty($this->output)) {
0038             return NULL;
0039         }
0040         return array_pop($this->output);
0041     }
0042 
0043     /**
0044      * Pushes an element onto the front of the queue.
0045      */
0046     public function push($x) {
0047         array_push($this->input, $x);
0048     }
0049 
0050     /**
0051      * Checks if it's empty.
0052      */
0053     public function isEmpty() {
0054         return empty($this->input) && empty($this->output);
0055     }
0056 }