Infix expression
Arithmetic symbols in the middle of numbers
Suffix expression
Arithmetic symbols after the number
The computer calculates the suffix expression.
Example of infix suffix
5 + 3, 5 3 +
1 + 2 * 3-1 2 3 * +
9 + (3-1) * 5, 9 3 1-5 * +
infix variable suffix algorithm
··· Iterating through the numbers and symbols in an infix expression
········· For numbers: Direct output
········· For symbols:
······················ Left parenthesis: Into the stack
······················ Symbol: Precedence comparison to top of stack symbol
································ Stack top symbol priority low, in-stack
································ Stack top symbol priority is not low, the top symbol pops up and output after the stack
······················ Closing parenthesis: Find the top of the stack popup and output until a matching opening parenthesis is found
··· The loop ends and all the symbols in the stack are ejected and output
Pseudo code
void transform (an array that needs to be traversed)
{
Create stacks;
int i;
while (judging if it loops to the end)
if (if a number)
{
Direct output
}
if (if the left sign)
{
Into the stack
}
if (if it is a symbol)
{
if (priority (current number precedence) = Priority (top element of the stack))
Stack top popup;
into the stack (regardless of the priority level needs to go into the stack);
}
if (right parenthesis)
{
while (the top of the stack is not an opening parenthesis)
Out of the stack;
}
Else
Error
}
Code
#include <stdio.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)
{
linkstack* stack = linkstack_create ();
int i = 0;
while (exp[i]! = ' + ')
{
if (Isnumber (Exp[i]))
{
Output (Exp[i]);
}
else if (Isoperator (Exp[i]))
{
while (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 = ' + ';
while (!isleft (char) (int) linkstack_top (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 ("+ + (3-1) *5+8/2");
printf ("\ n");
return 0;
}
Application of stacks---infix suffix