Data structure experiment stack 2: General arithmetic expressions are converted into suffixes Time Limit: 1000 ms memory limit: 65536 k any questions? Click Here ^_^ This topic describes how to convert an arithmetic expression based on binary operators into a corresponding suffix and output it. Enter an arithmetic expression with the '#' character as the ending sign. Output the suffix obtained by the expression conversion. Sample Input
a*b+(c-d/e)*f#
Sample output
ab*cde/-f*+
Prompt source sample program
Generally, the suffix is used:
1. Set up a stack for temporarily storing operators;
2. Set the end Of the expression to "#" and the end of the operator to "#".
3. If the current character is an operand, it is added to the stack;
4. If the priority of the current operator is higher than that of the stack top operator, go to the stack;
5. Otherwise, the exit operator is sent to the suffix;
6. The brackets "(" is used to isolate the operators after it, and ")" can be regarded as the ending character of the expression starting with the corresponding left bracket.
# Include <stdio. h> # include <string. h> # include <stdlib. h >#include <iostream >#include <algorithm> # include <stack> using namespace STD; int main () {stack <int> q; char STR [110]; int I; scanf ("% s", STR); for (I = 0; STR [I]! = '#'; I ++) {If (STR [I]> = 'A' & STR [I] <= 'Z ') // output directly when encountering letters; printf ("% C", STR [I]); else if (STR [I] = '(') // press the left brackets directly into the stack; q. push (STR [I]); else if (STR [I] = ') // when the right parenthesis is encountered; {While (Q. top ()! = '(') // If the top of the stack is not a left bracket, it means that the values in the brackets are not completely input, and {printf ("% C", Q. top (); q. pop ();} Q. pop (); // Delete the left parenthesis directly;} else if (STR [I] = '+' | STR [I] = '-') {While (! Q. Empty () & Q. Top ()! = '(') {Printf ("% C", Q. top (); q. pop ();} Q. push (STR [I]);} else if (STR [I] = '*' | STR [I] = '/') {While (! Q. Empty () & Q. Top ()! = '(' & (Q. top () = '*' | Q. top () = '/') {printf ("% C", Q. top (); q. pop ();} Q. push (STR [I]) ;}} while (! Q. empty () // If the stack is not empty at the end, it indicates that there is a backlog in the stack, and the output is at this time; {printf ("% C", Q. top (); q. pop () ;}cout <Endl; return 0 ;}
Zookeeper
Data structure experiment stack 2: General arithmetic expressions are converted into suffixes