Stack application-computing expression

Source: Internet
Author: User
Question: Give you an expression (of course a string) to evaluate the value of this expression. There is a simple method in Javascript that can be easily implemented, that is, Eval. The Code is as follows:

var expr = '-(-1)*(2+(7*5))';var ret = eval(expr);alert(ret);
If we write such a function ourselves, we need to use "Stacks. Stack is a special linear table. It follows the "first-in-first-out" principle and can only be retrieved from the top of the stack one by one at a time. Here we use JavaScript to simulate the stack. The Code is as follows:

// Simulate a stack function stack () {var stack ={}, Top =-1; return {// whether the stack is empty isempty: function () {return (Top =-1? True: false) ;}, // current value of the stack (top) curr: function () {return (top> = 0? Stack [Top]: NULL) ;}, // push: function (o) {++ top; stack [Top] = O ;}, // output stack, pop: function () {If (top <0) {return NULL;} var temp = stack [Top]; Delete stack [Top]; -- top; return temp ;}};}
The following code uses the stack to perform expression operations:
  1. Take two stacks, one for storing the numbers in the expression, and the other for storing symbols (+ ,-,*,/);
  2. Scans by characters starting with an expression. If it is a number, it is written into the number stack. If it is a symbol, it is case-based:
    • If the current symbol priority is greater than the symbol stack item priority, the current symbol is added to the symbol stack;
    • Otherwise, perform the following intermediate operations:
      • Two numbers are displayed from the number stack, marked as num1 and num2 respectively;
      • A symbol pops up from the symbol stack, marked #
      • Perform a simple arithmetic operation: ret = num2 # num1;
      • And re-enter the returned result RET into the digital stack;
    • After the intermediate operation is completed, the current symbol is added to the symbol stack;
  3. After the expression scan is complete, perform the intermediate operation until the symbol stack is empty;
The above thinking is only about the simplest arithmetic operation, and does not consider the processing when the symbol is parentheses. There are also some details. The following code is used for implementation (JavaScript language ):

Function calc (expr) {// digital stack, symbol stack, expression index, expression length, intermediate variable VAR Nums = new stack (), opers = new stack (), Index = 0, max = expr. length, num_temp = ''; // whether it is a symbol (operator or bracket) var iseries = function (CH) {If (CH = '+' | CH = '-' | CH = '*' | CH = '/' | CH = '( '| CH = ') ') {return true;} return false;}; // calculation priority var prec = function (priority) {If (response = '+' | response = '-') {return 1;} else if (response = '*' | | Outputs = '/') {return 2 ;}; // a simple and basic arithmetic operation for two numbers var getresult = function (num1, num2, callback) {Switch (callback) {Case '+': Return num2 + num1; break; Case '-': Return num2-num1; break; Case '*': Return num2 * num1; break; case '/': Return num2/num1; break ;}};/***** intermediate operation * records the two numbers in the number stack as num1, num2 * pops up a symbol * from the symbol stack and then computes the result, and re-enters the result into the digital stack */var middle_calc = function () {num1 = nums. pop (); // compatible if the first word in the expression It is '-', for example, '-(-1) * 2 + (7-5)'; // It is okay if it is not processed. // num2 = nums. pop (); num2 = nums. pop () | 0; cursor = opers. pop (); var ret = getresult (num1, num2, callback); nums. push (RET); // console. log (num2) ;}; // scan expression, perform the inbound operation while (true) {// The current scan character var CH = expr [Index]; // The current scan character is a number if (! Isnan (CH) {// number (to form multiple digits) num_temp + = CH; // The current scan character is used as the symbol} else if (isnan (CH )) {// the first digit of the current symbol is added to the digital stack, // and the intermediate variable of the spliced digit is cleared to splice the next digit if (num_temp! = '') {Nums. push (num_temp * 1); num_temp = '';} // the symbolic stack is empty or the current scanned symbol is '(' or when the stack in the symbolic stack is '(', // The scanned current symbol into the symbol stack if (opers. isempty () | CH = '(' | (opers. curr () = '(') {opers. push (CH); // when the symbol stack is not empty and the current Scanning symbol is Operator (+,-, *,/)} else if (Ch! = '(' & Ch! = ') {// The current scanned symbol has a higher priority than the top of the stack in the symbolic stack. // The scanned current symbol has a higher priority. If (Prec (CH)> prec (opers. curr () {opers. push (CH);} else {// the priority of the current scanned symbol. If the priority is never higher than that of the top stack of the symbolic stack, the intermediate operation while (Prec (CH) is always performed) -prec (opers. curr () <= 0) {middle_calc ();} // After the intermediate computation is completed, the scanned current symbol is imported into the symbol stack opers. push (CH);} // when the current scanned symbol is ')'} else if (CH = ')') {// if the top of the stack in the symbol stack is not '(', the intermediate operation while (opers. curr ()! = '(') {Middle_calc ();} // After the intermediate computation is complete, '('outbound stack outputs = opers. Pop ();}}
// Add the last number to the digital Stack
If (num_temp! = ''){
Nums. Push (num_temp * 1 );
Num_temp = '';
}
// Add 1 to the expression index to scan the next character + + index in the expression; // If (index> MAX) {break ;}/// the final operation after the scan is completed while (! Opers. isempty () {middle_calc ();} // the last one in the digital stack is the final operation result of the expression return nums. Pop ();}
Verification Result:

var expr = '-(-1)*(2+(7*5))';console.log(calc(expr));

Successful!

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.