Data Structure-evaluate the stack expression in C Language (Expression Tree)

Source: Internet
Author: User
Tags stack pop

Data Structure-evaluate the stack expression in C Language (Expression Tree)

Using the stack to implement expression tree I have two ideas here:

Part one:

 

First, judge each character of the input expression. If an operator is encountered,

Then the elements at the top of the two stacks are popped up, and the elements are carried out. Then, the result is pushed to the stack.

Code:

 

 

// Stack implementation expression // idea: the idea of this program is to read the input string and then judge each character. // when an operator is encountered, the operator is inferior to the stack, next, extract the two elements at the top of the stack, perform operations, and then press the result to the stack. // Yang Xin # include
 
  
# Include
  
   
Typedef int SElemType; // stack element type # define STACK_INIT_SIZE 10 // initial storage space allocation # define STACKINCREMENT 2 // storage space allocation increment/** sequence stack struct **/typedef struct SqStack {SElemType * base; // before and after stack construction, the base value is NULL SElemType * top; // stack top pointer int stacksize; // currently allocated storage space,} SqStack in element units;/** construct a stack **/int InitStack (SqStack * S) {// allocate a specified size of storage space (* S) to the bottom of the stack ). base = (SElemType *) malloc (STACK_INIT_SIZE * sizeof (SElemType); if (! (* S ). base) exit (0); // storage allocation failed (* S ). top = (* S ). base; // The same stack bottom and stack top indicate an empty stack (* S ). stacksize = STACK_INIT_SIZE; return 1;}/** get the top element of the stack **/int GetTop (SqStack S, SElemType * e) {if (S. top> S. base) {* e = * (S. top-1); // The next position of the stack top pointer is the stack top element return 1;} elsereturn 0;}/** inbound stack (pressure stack) **/int Push (SqStack * S, SElemType e) {if (* S ). top-(* S ). base> = (* S ). stacksize) // stack full, append storage space {(* S ). base = (SElemType *) realloc (* S ). base, (* S ). stacksize + STACKINCREMENT) * sizeof (SElemType); if (! (* S ). base) exit (0); // storage allocation failed (* S ). top = (* S ). base + (* S ). stacksize; (* S ). stacksize + = STACKINCREMENT;} * (* S ). top) ++ = e; // This equation has the same ++ * priority, but their calculation method is from right to left return 1 ;} /** output stack **/int Pop (SqStack * S, SElemType * e) {if (* S ). top = (* S ). base) return 0; * e = * -- (* S ). top; // This equation has the same ++ * priority, but their calculation method is from right to left return 1 ;} /** determine the priority **/SElemType Precede (SElemType t1, SElemType t2) {SElemType f; switch (t2) {case '+': case '-': if (T1 = '(' | t1 = '#') f = '<'; elsef = '>'; break; case '*': case '/': if (t1 = '*' | t1 = '/' | t1 = ') f ='> '; elsef =' <'; break; case '(': if (t1 = ') {printf (ERROR1); exit (0);} elsef =' <'; break; case ')': switch (t1) {case '(': f = '; break; case' # ': printf (ERROR2); exit (0); default: f = '>';} break; case '#': switch (t1) {case '#': f = '; break; case '(': printf (ERROR3); exit (0); default: f = '>';} return f;}/** search operator **/int In (SElemType c) {sw Itch (c) {case '+': case '-': case '*': case '/': case '(': case ')': case '#': return 1; default: return 0;}/** operation **/SElemType Operate (SElemType a, SElemType theta, SElemType B) {SElemType c; a = a-48; // convert the ASCII value to the corresponding decimal value B = b-48; // convert the ASCII value to the corresponding decimal value switch (theta) {case '+ ': c = a + B + 48; break; case '-': c = a-B + 48; break; case '*': c = a * B + 48; break; case '/': c = a/B + 48;} return c;}/** comparison operator priority **/SElemType EvaluateExpression () {SqStack OPTR, OPND; SElemType a, B, c, x, theta; InitStack (& OPTR); Push (& OPTR, '#'); InitStack (& OPND); c = getchar (); getTop (OPTR, & x); while (c! = '#' | X! = '#') {If (In (c) // switch (Precede (x, c) {case' <': Push (& OPTR, c); // low priority c = getchar (); break; case '=': Pop (& OPTR, & x ); // remove the brackets and accept a single character c = getchar (); break; case '>': Pop (& OPTR, & theta ); // stack back and import the operation result to the stack Pop (& OPND, & B); Pop (& OPND, & a); Push (& OPND, Operate (a, theta, b); break;} else if (c> = '0' & c <= '9')/c is the operand {Push (& OPND, c ); c = getchar ();} else // c is an invalid character {printf (invalid character !!); Exit (0) ;}gettop (OPTR, & x) ;}gettop (OPND, & x); return x ;}int main () {printf (enter an arithmetic expression, end with #); printf (for example, 3 * (7-5) #); printf (% c, EvaluateExpression (); return 0 ;}
  
 
Result:

 

 

 

 

Part two:

It is to press all input stacks with the operator stack and operation value stack respectively, and then an operator is displayed,

Two Operation values are displayed for calculation, and the result is then pushed to the stack.

 

 

Code: (C ++ Version)

 

// Stack implementation expression summation // stack implementation expression calculation // Yang Xin # include
 
  
# Include
  
   
# Include
   
    
# Include
    
     
# Include
     
      
Using namespace std; # define true 1 # define false 0 # define OPSETSIZE 8 typedef int Status; unsigned char Prior [8] [8] = {// operator priority table // + ''-''*''/''('') ''#'' ^ '/*' + '*/'> ','> ',' <','> ', '>', '<',/* '-' */'>', '>', '<', '> ', '>', '<',/* '/'> ',' <','> ', '>', '<',/* '/' */'>', '<', '> ', '>', '<',/* '(' */'<', '= ', '', '<',/* ')' */'>', '>', ','> ', '> ', '>',/* '#' */'<', '<', '', '= ', '<',/* '^' */'>', '<', '>', '> ', '>'}; Typedef struct StackChar {char c; struct StackChar * next;} SC; // SCtypedef struct StackFloat {float f; struct StackFloat * next ;} SF; // StackFloat node SFSC * Push (SC * s, char c) // SC type pointer Push, returns p {SC * p = (SC *) malloc (sizeof (SC); p-> c = c; p-> next = s; return p;} SF * Push (SF * s, float f) // pointer Push of SF type, returns p {SF * P = (SF *) malloc (sizeof (SF); p-> f = f; p-> next = s; return p;} SC * Pop (SC * s) // SC type pointer Pop {SC * q = s; s = s-> next; free (q); return s;} SF * Pop (SF * s) // SF-type pointer Pop {SF * q = s; s = s-> next; free (q); return s;} float Operate (float a, unsigned char theta, float B) // calculate the function Operate {switch (theta) {case '+': return a + B; case '-': return a-B; case '*': return a * B; case '/': return a/B; case '^': return pow (a, B); default: Return 0 ;}} char OPSET [OPSETSIZE] = {'+ ','-','*','/','(',')','#', '^'}; Status In (char Test, char * TestOp) {int Find = false; for (int I = 0; I <OPSETSIZE; I ++) {if (Test = TestOp [I]) Find = true;} return Find;} Status ReturnOpOrd (char op, char * TestOp) {for (int I = 0; I <OPSETSIZE; I ++) {if (op = TestOp [I]) return I ;}} char precede (char Aop, char Bop) {return Prior [ReturnOpOrd (Aop, OPSET)] [ReturnOpOrd (Bop, OPS ET)];} float EvaluateExpression (char * MyExpression) {// operator priority algorithm used to evaluate the arithmetic expression // set OPTR and OPND as the operator stack and arithmetic stack respectively, OP is the set of operators SC * OPTR = NULL; // operator stack, character element SF * OPND = NULL; // number stack, real element char TempData [20]; float Data, a, B; char theta, * c, Dr [] = {'#', ''}; OPTR = Push (OPTR, '#'); c = strcat (MyExpression, dr); strcpy (TempData,); // string copy function while (* c! = '#' | OPTR-> c! = '#') {If (! In (* c, OPSET) {Dr [0] = * c; strcat (TempData, Dr); // string connection Function c ++; if (In (* c, OPSET) {Data = atof (TempData); // String Conversion Function (double) OPND = Push (OPND, Data); strcpy (TempData ,);}} else // if it is not an operator, go to the stack {switch (precede (OPTR-> c, * c) {case' <': // The top element of the stack has a low priority OPTR = Push (OPTR, * c); c ++; break; case '= ': // parentheses and one character OPTR = Pop (OPTR); c ++; break; case '> ': // stack back and import the calculation result to the stack theta = OPTR-> c; OPTR = Pop (OPTR); B = OPND-> f; OPND = Pop (OPND ); a = OPND-> f; OPND = Pop (OPND); OPND = Push (OPND, Operate (a, theta, B); break ;} // switch }}// while return OPND-> f;} // EvaluateExpression int main (void) {char s [128]; puts (enter the expression :); gets (s); puts (the expression value is :); printf (% s = % g, s, EvaluateExpression (s); system (pause); return 0 ;}
     
    
   
  
 

Result:

 

 

 

Related Article

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.