从网上找的韩顺平老师算法讲解的 使用堆栈 实现计算器
<?php
namespace Library;
use Helper\Common;
class StackCalculateor { public $top = -1;
public $maxSize = 15;
public $stack = array();
public static function run($str) { $numsStack = new self(); $operStack = new self();
$index = 0;
$keepNum = '';
if (!mb_strlen($str)) return false;
while (true) { $val = mb_substr($str, $index, 1);
if ($operStack->isOper($val) == true) { if ($operStack->isEmpty()) { $operStack->push($val); } else { while (!$operStack->isEmpty() && $operStack->PRI($val) <= $operStack->PRI($operStack->getTop())) { $num1 = $numsStack->pop(); $num2 = $numsStack->pop(); $oper = $operStack->pop(); $res = $numsStack->getResult($num1, $num2, $oper); $numsStack->push($res); } $operStack->push($val); }
} else { $keepNum .= $val; if ($index == mb_strlen($str) - 1) { $numsStack->push($keepNum); } else { if ($operStack->isOper(mb_substr($str, $index + 1, 1))) { $numsStack->push($keepNum); $keepNum = ''; } } }
$index++;
if ($index == mb_strlen($str)) break; }
while (!$operStack->isEmpty()) { $num1 = $numsStack->pop(); $num2 = $numsStack->pop(); $oper = $operStack->pop(); $res = $numsStack->getResult($num1, $num2, $oper); $numsStack->push($res); }
return $res; }
public function isOper($val) { if ($val == '+' || $val == '-' || $val == '*' || $val == '/') return true; }
public function isEmpty() { if ($this->top == -1) return true; }
public function push($val) { if ($this->top == $this->maxSize - 1) return;
$this->top++;
$this->stack[$this->top] = $val; }
public function pri($oper) { if ($oper == '*' || $oper == '/') return 1; else if ($oper == '+' || $oper == '-') return 0; }
public function getTop() { return $this->stack[$this->top]; }
public function pop() { if ($this->top == -1) return null;
$topVal = $this->stack[$this->top];
$this->top--;
return $topVal;
}
public function getResult($num1, $num2, $oper) { switch ($oper) { case '+': $res = Common::sbcadd($num2, $num1); break; case '-': $res = Common::sbcsub($num2, $num1); break; case '*': $res = Common::sbcmul($num2, $num1); break; case '/': $res = Common::sbcdiv($num2, $num1); break; }
return $res; }
public function showStack() { if ($this->top == -1) return;
echo '当前栈的情况是....', PHP_EOL;
for ($i = $this->top; $i > -1; $i--) { echo ' stack[' . $i . ']=' . $this->stack[$i], PHP_EOL; } }
}
|