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.