For more information about the stack API, see my other blog post: Chained storage for stacks-API implementations
Instance:
5 + 4=> 5 4 +
1 + 2 * 3 = 1 2 3 * +
8 + (3–1) * 5 = 8 3 1–5 * +
Infix expression conforms to human reading and thinking habits
The suffix expression conforms to the computer's "operating Habits"
infix suffix algorithm:
Iterating through the numbers and symbols in an infix expression
For numbers: Direct output
For symbols:
Left parenthesis: Into the stack
Operational symbols: Precedence compared to top of stack symbols
If the stack top symbol priority is low: this conforms to the stack (the default stack top if the opening parenthesis, the left parenthesis the lowest priority)
If the stack top symbol priority is not low: the stack top symbol is ejected and output, and then into the stack
Closing parenthesis: POPs the top of the stack and outputs it until it matches the opening parenthesis
Traversal end: Eject and output all symbols in the stack
infix suffix
Main code:
#include "stdio.h" #include "stdlib.h" #include "string.h" #include "linkstack.h" int isnumber (char c) {return (' 0 ' <= c) && (c <= ' 9 ');} int Isoperator (char c) {return (c = = ' + ') | | (c = = '-') | | (c = = ' * ') | | (c = = '/');} int Isleft (char c) {return (c = = ' (');} int Isright (char c) {return (c = = ') ');} int priority (char c) {int ret = 0;if (c = = ' + ') | | (c = = '-')) {ret = 1;} if ((c = = ' * ') | | (c = = '/')) {ret = 2;} return ret;} void output (char c) {if (c! = ') ' {printf ("%c", c);}} void transform (const char* exp) {int i = 0; linkstack* stack = Linkstack_create (); while (exp[i]! = ' + ') {if (Isnumber (Exp[i])) {output (exp[i]);} else if (Isoperator (Exp[i])) {while (priority (Exp[i)) <= priority ((char) (int) linkstack_top (stack)) {output (char) (int) Linkstack_pop (Stack));} Linkstack_push (Stack, (void*) (int) exp[i]);} else if (Isleft (Exp[i])) {Linkstack_push (Stack, (void*) (int) exp[i]);} else if (Isright (Exp[i])) {//char c = ' linkstack_top '; while (!isleft (char) (int) (stack)) {output (char) (int) Linkstack_pop (Stack));} Linkstack_pop (stack);} else{printf ("Invalid expression!"); break;} i++;} while ((Linkstack_size (Stack) > 0) && (exp[i] = = ()) {output (char) (int) linkstack_pop (stack));} Linkstack_destroy (stack);} int main () {transform ("8+ (3-1)");p rintf ("\ n"), System ("pause"); return 0;}
Full project Details: Github
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Application of stack-suffix expression to infix expression