php 队列类

<?php
/** 
 * PHP Class for queue 
 * @author yangqijun@live.cn 
 * @copyright DataFrog Beijingbei  Ltd. 2011-07-25 
 */  
class Queue {  
    public  $length=12;          //默认队列,相当于初始化队列
    public  $queue  = array();  //  if String like this "22,23,24"    convert to array to do queue  
    public  $delimiter=',';  

    function __construct($queue=array())  
    {  
        $this->queue=$queue;
    }  
    /** 
     * @desc start queue 
     * @param String  $param  new queue element 
     */  
    public function run($param)  
    {   
        if(!is_array($this->queue)){  
            $this->strToQue();//将数组视为队列 
        }  
        $currentlength=$this->countqueue();        //Count  the  queue length
        echo $currentlength;
        echo $this->length.'<br>';   
        if($currentlength<$this->length&&$this->length>0) {  
            $this->queAdd($param);  
        }else if($this->length==0)  //如果为空队列,则将队列初始化为输入的队列
        {  
            $param=empty($param)?0:$param;  
            $this->queue[]=$param;  
        }  
        else {              
            for ($i=0;$i<$currentlength-$this->length-1;$i++)//队列比规定的队列多,要删掉队首的元素,才能入队
            {  
                $this->queRemove();  
            }  
            $this->queAdd($param);  
        }               
        return $this->queue;               
    }  
    /** 
     * String like this "22,23,24"  convert to array to do queue 
     * @param String $string 
     * @param String $delimiter 
     */  
    public function strToQue (){    
        if (empty($this->queue))  
        {  
            $this->queue=array();  
        }  
        else  
        {  
            $this->queue=explode($this->delimiter,$this->queue);  
        }       
    }  
    /** 
     * insert $node into queue 
     * @param string $node 
     */  
    private function queAdd($node){      
        array_push($this->queue,$node);  
        $this->countqueue();  
    }  
    private function queRemove(){  
        $node = array_shift($this->queue);  
        $this->countqueue();  
        return $node;  
    }  
    private function countqueue(){  
        $currentlength= count($this->queue);  
        return $currentlength;  
    }  
    function __destruct()  
    {  
        unset($this->queue);  
    }  
}   
//example  
$str='88|89|90|56|23|45|69|23|20|100'; 
$obj=new Queue ($str); 
$obj->length=8;  // 队列元素长度  
$obj->delimiter='|';  //如果队列是字符串,则元素直接的分隔符为| 
$a=$obj->run('91');   //要添加到队列中的元素 
$a=$obj->run('92');  
$a=$obj->run('93');  
$a=$obj->run('94');  
print_r($a);
?>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值