关于php中栈的基本操作
本人算法小白,前几天做过链表的递归翻转之后,对算法产生兴趣,今天在纠结了一个小时的栈的算法终于搞定了,由于网上php相关的栈的基本操作很少,现贴出来给大家参考,大神绕路,不喜勿喷谢谢。
<?php
/**
* Created by PhpStorm.
* User: user
* Date: 07/03/2017
* Time: 21:35
*/
class node{
private $value;
private $pre;
public function __construct($value){
$this->value = $value;
$this->pre = null;
}
public function addPre($node){
$this->pre = $node;
}
public function getPre(){
return $this->pre;
}
public function getValue(){
return $this->value;
}
}
class stack{
private $top;
static public $size;
public function __construct($value){
$this->top = new node($value);
}
public function push($value){
$current = $this->top;
$newNode = new node($value);
$newNode->addPre($current);
$this->top = $newNode;
}
public function getAllStack(){
$stack = null;
$current = $this->top;
while ($current->getPre() != null){
$stack .= $current->getValue()."\n";
$current = $current->getPre();
}
return $stack;
}
public function getSize(){
$current = $this->top;
while (null != $current->getValue()){
self::$size++;
$current = $current->getPre();
}
return self::$size;
}
public function pop(){
$current = $this->top;
$this->top = $current->getPre();
unset($current);
}
public function getTop(){
return $this->top->getValue();
}
}
$stack = new stack(0);
$stack->push(1);
$stack->push(2);
$stack->push(3);
$stack->push(4);
$stack->push(5);
$stack->push(6);
$stack->push('a');
$stack->push('b');
$stack->push('c');
$stack->push('d');
echo "无出栈顺序:".$stack->getAllStack()."<br>";
$stack->pop();
$stack->pop();
$stack->pop();
echo "三次出栈后:".$stack->getAllStack()."<br>";
echo "此时的栈顶元素:".$stack->getTop()."<br>";
echo "栈的长度为:".$stack->getSize()."<br>";
?>