Stack application example-arithmetic operation

Source: Internet
Author: User

This example is from the stack section of Yan Weimin's data structure. However, I made some simple modifications to ensure that the compilation was successful.

Objective: To use the stack to calculate the result of a string arithmetic operation such as "3*(7-2. There are 3 code files in total, as shown below:

1. mystack. h

#pragma once#define maxsize 30typedef struct{char data[maxsize+1];    int top;}Stack;int Push(Stack& S,char x);int Pop(Stack& S,char& x);char readtop(Stack S);

2. mystack. cpp

#include "mystack.h"#include "stdio.h"int Push(Stack& S,char x){if (S.top==maxsize){printf("overflow\n"); return(0);}S.data[++S.top]=x; return(1);}int Pop(Stack& S,char& x){if(S.top==0){printf("undertflow\n");return(0);}x=S.data[S.top]; S.top--;return(1);}char readtop(Stack S){char a;          a=S.data[S.top]; return(a);}

3. caclstack. cpp

#include 
 
  #include 
  
   #include "mystack.h"using namespace std;double operate(char ch, double x,double y);int precede(char p1,char p2);double calcul(char a[]);
  
 
 
// This is the main function int main () {char tmp [] = "3 * (7-2) #"; // The input string must end. // Char tmp [] = "3 * (7-2) + 5*2 #"; double rst = calcul (tmp); cout <
 
  
'#' | Readtop (S1) <> '#') while (r! = '#' | Readtop (S1 )! = '#') {If (r <= '9' & r> = '0') {x = 0; while (r <= '9' & r> = '0') {x = x * 10 + r-'0'; r = a [++ I];} push (S2, x);} else switch (precede (readtop (S1), r) {case-1: Push (S1, r ); r = a [++ I]; break; // puts the operator into the stack 1 case 0: Pop (S1, ch); r = a [++ I]; // r = a [I]; break; // Pop an operator case 1: Pop (S1, ch); Pop (S2, x1); Pop (S2, x2 ); push (S2, operate (ch, x2, x1); // r = a [++ I]; r = a [I]; break ;}} return (readtop (S2 ));}
 


The above code is compiled in VS and the execution result is correct.

Note: The stack in this article uses the custom mystack.

For more information, see the data structure section of Yan Weimin.

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.