栈和队的定义---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中;
通过队实现栈:
维护2个队 $q1,$q2 =>$s
pop:当判断$q1 $q2谁为空,则不为空的出队,为空的入队,直到不为空的已存在一个元素,则为栈的pop
push:当判断$q1 $q2谁为空,,不为空的入队,均为空则入$q1
通过栈实现队
通过队实现栈
通过栈实现队
维护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(); } } }
相关文章推荐
- Android RRO机制的运用-----google开机向导客制化
- Linux下安装MySQL-5.7
- Servlet实现文件上传
- Servlet实现文件上传
- namespace
- 通过项目逐步深入了解Mybatis<一>
- Windows 配置PHP7开发环境
- RecyclerView布局的点击(并非item的点击)
- tableView为UITableViewStyleGrouped时,组与组之间会有一点间隙
- servlet教程
- Linux系统中‘dmesg’命令处理故障和收集系统信息的7种用法
- Objective-c - 当属性的类型是oc对象的时候,setter方法的写法
- windows socket 客户端
- POI使用:用poi接口不区分xls/xlsx格式解析Excel文档(41种日期格式解析方法,5种公式结果类型解析方法,3种常用数值类型精度控制办法)
- 截取车辆正样本
- RecyclerView下拉刷新、上拉加载框架<一>
- dialog dismiss时键盘不消失的问题浅析及解决办法
- 数组指针和指针数组
- 小物件之输出简单的table
- StringBuilder跟StringBuffer