您的位置:首页 > 其它

栈和队的定义---2

2017-01-09 17:15 363 查看
栈和队的定义---2

通过栈实现队
通过队实现栈
通过栈实现队

   维护2个栈,$s1,$s2; =>$queue

   例如 1 2 3 4 5 

 pop: 当$s1 作为入栈,$s2 出栈。当pop时,判断$s2是否为空,不为空则输出栈顶元素;当$s2为空,则把$s1的元素出栈 然后存在$s2中入栈,直到$s1 只存在一个元素,即为队的pop

当push时,直接存在$s1中;

class queue{
public $size;
public  $s1;//入栈
public  $s2;//出栈
public function __construct() {
$this->s1=new Stack();
$this->s2=new Stack();
$this->size=0;
}
function enqueue($value)
{
$this->s1->push($value);
$this->size++;
}
function popqueue()
{
if(!($this->s2->isEmpty()))
{
$top=$this->s2->getTop();
$this->s2->pop();
$this->size--;
return $top;
} else
{
while(($this->s1->size)>1)
{
$this->s2->push($this->s1->getTop());
$this->s1->pop();
}
$top=$this->s1->getTop();
$this->s1->pop();
$this->size--;
return $top;
}
return false;
}
}


通过队实现栈:

  维护2个队 $q1,$q2 =>$s

pop:当判断$q1 $q2谁为空,则不为空的出队,为空的入队,直到不为空的已存在一个元素,则为栈的pop

push:当判断$q1 $q2谁为空,,不为空的入队,均为空则入$q1

class stack
{
public $q1;
public $q2;
function stack{
$this->q1=new queque();
$this->q2=new queque();
}
public  function push($value){
if(!$this->q2->isempty())
$this->q2->push($value);
$this->q1->push($value);

}
public function pop(){
if($this->q1->isempty()&&$this->q2->isempty()) return -1;
if(!$this->q1->isempty()) {
while ($this->q1->size > 1) {
$value = $this->q1->front->value;
$this->q2->push($value);
$this->q1->pop();
}
return $this->q1->pop();
}else{
while ($this->q2->size > 1) {
$value = $this->q2->front->value;
$this->q1->push($value);
$this->q2->pop();
}
return  $this->q2->pop();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: