PHP implements the stack-based suffix expression evaluate function, and php suffix expression evaluate

Source: Internet
Author: User

PHP implements the stack-based suffix expression evaluate function, and php suffix expression evaluate

This example describes how to evaluate a stack-based suffix expression in PHP. We will share this with you for your reference. The details are as follows:

Suffix expression Overview

Suffix expression, which does not contain parentheses. Operators are placed behind two calculation objects. All calculation operations are performed in the order in which operators appear, strictly go from left to right (the priority rules of operators are not considered ).

Implementation Code:

<?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();?>

Running result:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.