PHP教程之PHP實現基於棧的尾碼運算式求值功能

來源:互聯網
上載者:User
尾碼運算式是什嗎?尾碼運算式,指的是不包含括弧,運算子放在兩個運算對象的後面,所有的計算按運算子出現的順序,嚴格從左向右進行(不再考慮運算子的優先規則)。本文PHP教程主要是用執行個體講述PHP實現基於棧的尾碼運算式求值功能。分享給大家供大家參考,具體如下:

實現代碼:

<?phpclass Stack{  public $stack;  public $stack_top;  public function __construct(){    $this->stack=array();    $this->stack_top=-1;  }  public function push($data){    $this->stack[]=$data;    $this->stack_top++;  }  public function pop(){    if(!$this->is_empty())    {      $this->stack_top--;      return array_pop($this->stack);    }else    {      echo "stack is empty";    }  }  public function is_empty(){    if($this->stack_top==-1)    return true;  }}$string="1243-*+63/-";$arrs=str_split($string);echo var_export($arrs);$stack=new Stack();foreach($arrs as $arr){  switch($arr){    case "+":$one=$stack->pop();$two=$stack->pop();$temp=$two + $one;$stack->push($temp);break;    case "-":$one=$stack->pop();$two=$stack->pop();$temp=$two - $one;$stack->push($temp);break;    case "*":$one=$stack->pop();$two=$stack->pop();$temp=$two * $one;$stack->push($temp);break;    case "/":$one=$stack->pop();$two=$stack->pop();$temp=$two / $one;$stack->push($temp);break;    default:$stack->push($arr);  }}echo $stack->pop();?>

運行結果:

array (
0 => '1',
1 => '2',
2 => '4',
3 => '3',
4 => '-',
5 => '*',
6 => '+',
7 => '6',
8 => '3',
9 => '/',
10 => '-',
)1

學完本文大家肯定都對尾碼運算式有所瞭解,並且也學會了如何用PHP實現基於棧的尾碼運算式求值功能,這種方法對於程式員來說很有用處,後期會介紹更多相關內容和大家共勉。

希望本文所述對大家PHP程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.