【面试题】用php实现一个双向队列

主旨:主要是考数组的函数

  • array_pop    array_push  
    array_pop   array_pop() 函数删除数组中的最后一个元素。删除尾部一
    array_push    array_push() 函数向第一个参数的数组尾部添加一个或多个元素(入栈),然后返回新数组的长度。
    该函数等于多次调用 $array[] = $value。 尾部塞入一
     
  • array_unshift    array_shift  
    array_shift()       函数删除数组中第一个元素,并返回被删除元素的值。 删除头第一
    array_unshift()      函数用于向数组插入新元素。新数组的值将被插入到数组的开头。 插入头第一
    
     
  • reset    end  
    reset   reset() 函数将内部指针指向数组中的第一个元素,并输出。
    end    end() 函数将数组内部指针指向最后一个元素,并返回该元素的值(如果成功)。

实现代码:

<?php
class Deque  
{ 
    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); 
    }
    
}

猜你喜欢

转载自demonli.iteye.com/blog/2365990