定义
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
代码实现
建立在这篇文章的基础上链表的实现
class LinkListQueue extends LinkList {
public $tail; //尾结点
/**
* @param mixed $val
* @return
*/
public function push($val){
if($this->head->val == null){
$this->tail = new Node($val);
$this->head = $this->tail;
} else {
$this->tail->next = new Node($val);
$this->tail = $this->tail->next;
}
$this->size++;
}
/**
* @param
* @return mixed
*/
public function pop(){
if($this->size <= 0){
return null;
}
$val = $this->head->val;
$this->head = $this->head->next;
$this->size--;
return $val;
}
}
测试
$queue = new LinkListQueue();
$queue->push("aaaaaa");
$queue->push("cccc");
print_r($queue);
$queue->pop();
print_r($queue);
输出结果
LinkListQueue Object
(
[tail] => Node Object
(
[val] => cccc
[next] =>
)
[head] => Node Object
(
[val] => aaaaaa
[next] => Node Object
(
[val] => cccc
[next] =>
)
)
[size] => 2
[map] => Array
(
)
)
LinkListQueue Object
(
[tail] => Node Object
(
[val] => cccc
[next] =>
)
[head] => Node Object
(
[val] => cccc
[next] =>
)
[size] => 1
[map] => Array
(
)
)