php的array 很强大,自带很多数组函数,可以直接当作数组,队列,栈,集合,字典来用
<?php
#php5 没有内部类??
class Node{
public $item;
public $next;
}
class Stack{
private $first;
private $n;
function __construct(){
$this->first=null;
$this->n=0;
}
function isEmpty(){
return $this->first==null;
}
function size(){
return $this->n;
}
function push($item){
$oldfirst=$this->first;
$this->first=new Node();
$this->first->item=$item;
$this->first->next=$oldfirst;
$this->n++;
}
function pop(){
if($this->isEmpty())
throw new Exception('no such element');
$item=$this->first->item;
$this->first=$this->first->next;
$this->n--;
return $item;
}
function peek(){
if($this->isEmpty())
throw new Exception('no such element');
return $first->item;
}
}
#首先,php的array函数 自带栈的功能
$a[]=1;
$a[]=2;
$a[]=3;
$a[]=4;
$a[]=5;
array_push($a, 6);
print_r($a);
print_r(array_pop($a));
print_r($a);
#Stack类 测试如下
try{
$stack=new Stack();
print_r($stack);
$stack->push(1);
$stack->push(2);
$stack->push(3);
$stack->push(4);
$stack->push(5);
print_r($stack->peek());
print_r($stack);
print_r($stack->pop());
print_r($stack);
}catch(Exception $e){
echo $e->getMessage();
}