佇列是先進先出的資料結構,先塞進來的資料就必須先取出。
class Queue{
private $head=0,$tail=0;
private $max=100;
private $data=array();
private $error;
public function pop(){
if($this->head != $this->tail){
$this->head++;
if($this->head >$this->max){
$this->head = $this->head -$this->max - 1;
}
$data = $this->data[$this->head];
unset($this->data[$this->head]);
return $data;
}
}
public function push($data){
$original=$this->tail;
$this->tail++;
if($this->tail >$this->max){
$this->tail = $this->tail - $this->max -1;
}
if($this->tail == $this->head){
$this->error='佇列已滿';
$this->tail=$original;
return false;
}else{
$this->data[$this->tail]=$data;
return true;
}
}
public function showQueue(){
foreach($this->data as $key=>$value){
echo $key.'=>'.$value."\n";
}
}
}
$queue=new Queue();
for($i=0;$i<=2000;$i++){
$queue->push($i);
}
for($i=0;$i<39;$i++){
$queue->pop();
}
for($i=0;$i<100;$i++){
$queue->push($i);
}
$queue->showQueue();
程式碼解說:
Queue::pop() 取出資料
Queue::push() 塞進資料
Queue::showQueue() 列出佇列內的所有資料
沒有留言:
張貼留言