PHP實現一個雙向隊列例子

來源:互聯網
上載者:User

雙端隊列(deque)是由一些項的表組成的資料結構,對該資料結構可以進行下列操作:

    push(D,X) 將項X 插入到雙端隊列D的前端
    pop(D) 從雙端隊列D中刪除前端項並將其返回
    inject(D,X) 將項X插入到雙端隊列D的尾端
    eject(D) 從雙端隊列D中刪除尾端項並將其返回

PHP實現代碼

 代碼如下 複製代碼
<?php
class DoubleQueue 
{
    public $queue = array();
    
    /**(尾部)入隊  **/
    public function addLast($value) 
    {
        return array_push($this->queue,$value);
    }
    /**(尾部)出隊**/
    public function removeLast() 
    {
        return array_pop($this->queue);
    }
    /**(頭部)入隊**/
    public function addFirst($value) 
    {
        return array_unshift($this->queue,$value);
    }
    /**(頭部)出隊**/
    public function removeFirst() 
    {
        return array_shift($this->queue);
    }
    /**清空隊列**/
    public function makeEmpty() 
    {
        unset($this->queue);
    }
    
    /**擷取列頭**/
    public function getFirst() 
    {
        return reset($this->queue);
    }
 
    /** 擷取列尾 **/
    public function getLast() 
    {
        return end($this->queue);
    }
 
    /** 擷取長度 **/
    public function getLength() 
    {
        return count($this->queue);
    }
    
}

例子

編寫支援雙端隊伍的常式,每種操作均花費O(1)時間

 代碼如下 複製代碼

<?php
class deque
{
 public $queue  = array();
 public $length = 0;
  
 public function frontAdd($node){
  array_unshift($this->queue,$node);
  $this->countqueue();
 }
 public function frontRemove(){
  $node = array_shift($this->queue);
  $this->countqueue();
  return $node;
 }
  
 public function rearAdd($node){
  array_push($this->queue,$node);
  $this->countqueue();
 }
 
 public function rearRemove(){
  $node = array_pop($this->queue);
  $this->countqueue();
  return $node;
 }
 
 public function countqueue(){
  $this->length = count($this->queue);   
 }
}
$fruit = new deque();
echo $fruit -> length;
$fruit -> frontAdd("Apple");
$fruit -> rearAdd("Watermelon");
echo '<pre>';
print_r($fruit);
echo '</pre>';
?>

結果

0
deque Object
(
    [queue] => Array
        (
            [0] => Apple
            [1] => Watermelon
        )
    [length] => 2
)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.