array_unshift() 函数用于向数组插入新元素。新数组的值将被插入到数组的开头。
array_push() 函数向第一个参数的数组尾部添加一个或多个元素(入栈),然后返回新数组的长度。
array_shift() 函数删除数组中第一个元素,并返回被删除元素的值。

array_pop() 函数删除数组中的最后一个元素。返回数组的最后一个值。如果数组是空的,或者非数组,将返回 NULL。

运行代码:


<?php
    header("Content-type: text/html; charset=utf-8");
    function dump($res){
        echo "<pre>";
        var_dump($res);
        echo "</pre>";     
    }
    //双向队列类 
    class Deque{
        public $queue;
        public function __construct($data=array()){
            $this->queue = $data;
        }
        public function addFirst($item){
            return array_unshift($this->queue,$item);
        }
     
        public function addLast($item){
            return array_push($this->queue,$item);
        }
        public function removeFirst(){
            return array_shift($this->queue);
        }
        public function removeLast(){
            return array_pop($this->queue);
        }
    }
    // test
    $arr = array(
        "1",'4','2'
    );
    $obj = new Deque($arr);
    echo "从头部插入<br/>";
    $res = $obj->addFirst("3");
    dump($obj->queue);
    // 从尾部插入
    echo "从尾部插入<br/>";
    $res = $obj->addLast("5");
    dump($obj->queue);
    // 从头部删除,返回删除的元素
    echo "从头部删除,返回删除的元素<br/>";
    $res = $obj->removeFirst();
    dump($res);
    // 从尾部删除,返回删除的元素
    echo "从尾部删除,返回删除的元素<br/>";
    $res = $obj->removeLast();
    dump($res);
    echo "--------------------------<br/>";
    dump($obj->queue);
?>

运行结果



从头部插入
array(4) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "4"
  [3]=>
  string(1) "2"
}
从尾部插入
array(5) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "1"
  [2]=>
  string(1) "4"
  [3]=>
  string(1) "2"
  [4]=>
  string(1) "5"
}
从头部删除,返回删除的元素
string(1) "3"
从尾部删除,返回删除的元素
string(1) "5"
--------------------------
array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "4"
  [2]=>
  string(1) "2"
}

相关评论(0)
您是不是忘了说点什么?

友情提示:垃圾评论一律封号...

还没有评论,快来抢沙发吧!