栈和队均可以采用链表实现和数组实现
class node
{
public $value;
public $next;
function node($value=null){
$this->value=$value;
$this->next=null;
}
}
class stack
{
public $top;
public $bottom;
function stack(){
$this->top=$this->bottom=new node();
}
function push($value){
$this->top->value=$value;
$n=new node();
$n->next=$this->top;
$this->top=$n;
}
function pop(){
if($this->top==$this->bottom)
return -1;
$n=$this->top;
$value=$n->value;
$this->top=$this->top->next;
unset($n);
return $value;
}
function isempty(){
if($this->top==$this->bottom)
return true;
return false;
}
function gettop()
{
if($this->top==$this->bottom)
return -1;
return $this->top->next->value;
}
function printstack()
{
$p=$this->top;
while($p!=$this->bottom)
{
echo $p->next->value;
}
}
function _destruct()
{
$p=$this->top;
while($p!=$this->bottom){
$p1=$p;
$p=$p->next;
unset($p1);
}
unset($this->top);
unset($this->bottom);
}
}
栈定义:先进后出
建立时top=bottom指向空节点,top始终指向栈顶元素的前一个位置。
或者存储结构为数组:
class Stack {
private $stack;
public $size;
public function __construct() {
$this->stack = array();
$this->size = 0;
}
public function push($data) {
$this->stack[$this->size++] = $data;
return $this;
}
public function pop() {
if (!$this->isEmpty()) {
$top=$this->stack[--$this->size];
return array_pop($this->stack);
}
return FALSE;
}
public function getStack() {
return $this->stack;
}
public function getTop() {
if (!$this->isEmpty()) {
return $this->stack[$this->size - 1];
}
return FALSE;
}
public function getSize() {
return $this->size;
}
public function isEmpty() {
return 0==$this->size;
}
function _destruct()
{
}}unset($this->stack);
队,先后先出
class queque { public $front; public $rear; public $size; function queque(){ $this->front=$this->rear=new node(); $this->size=0; } function push($value){ $this->rear->value =$value; $n = new node(); $this->rear->next = $n; $this->rear = $n; $this->size++; } function pop(){ if($this->front==$this->rear) { return -1; }else { $value = $this->front->value; $this->front = $this->front=$this->front->next; } $this->size--; return $value; } function isempty(){ if($this->front==$this->rear) return true; return false; } }class Queue { public $queue; private $size; public function __construct() { $this->queue = array(); $this->size = 0; } function push($value) { array_unshift($this->queue, $value); $this->size++; return $this->queue; } function pop() { if($this->size>0){ $this->size--; return array_pop($this->queue); } return false; } public function isEmpty() { return 0==$this->size; } public function getSize() { return $this->size; }
function _destruct()
unset($this->queue);}{