后缀表达式
先建立栈,写出建立函数,push和pop函数,取栈顶元素值函数。
例:a+b*c+(d /e-f)*g 得到后缀表达式 abc *+de /f-g *+
当读到字母时则直接输出,当读到符号时做判断。
相关必要函数
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ERROR -1
typedef struct Stack{
char* base;
char* top;
int Stackhigh;
}Stack;
void initstack(Stack& s)
{
s.base=(char*)malloc(STACK_INIT_SIZE*sizeof(char));
if(!s.base) exit(ERROR);
s.top=s.base;
s.Stackhigh=STACK_INIT_SIZE;
}
void Push(Stack& s,char e)
{
if(s.top-s.base>=s.Stackhigh)
{
char* newbase=(char*)realloc(s.base,STACKINCREMENT*sizeof(char));
if(!newbase) exit(ERROR);
s.base=newbase;
s.top=s.base+s.Stackhigh;
s.Stackhigh+=STACKINCREMENT;
}
*s.top=e;
s.top++;
}
char Pop(Stack& s)
{
char e;
if(s.base==s.top) return;
s.top--;
e=*s.top;
return e;
}
char top(Stack& s)//用e取出栈顶的值,并返回
{
char e;
e=*(s.top-1);
return e;
}
如果见到(+,(,* ) ,那么从栈中弹出元素直到发现优先级更低的元素
此时见到(,在这种情况下他的优先级最高,直接放入栈,有一个例外,除非在处理一个)时,否则不弹出( 。
有了这个例外,当读到 * 时,即使( 优先级高于* ,也不会将( 弹出。
int main()
{
Stack s;
initstack(s);
char c[100]="a+b*c+(d/e-f)*g";
for(int i=0;i<strlen(c);i++)
{
char n=c[i];
if(n=='a'||n=='b'||n=='c'||n=='d'||n=='e'||n=='f'||n=='g') printf("%c",n);
else if(n=='+'||n=='-')
{
while(top(s)=='*'||top(s)=='+'||top(s)=='/'||top(s)=='-')
{
printf("%c",Pop(s));
}
Push(s,n);
}
else if(n=='*'||n=='/')
{
while(top(s)=='*'||top(s)=='/')
{
printf("%c",Pop(s));
}
Push(s,n);
}
else if(n=='(')
{
Push(s,n);
}
else if(n==')')
{
while(top(s)=='*'||top(s)=='+'||top(s)=='/'||top(s)=='-')
{
printf("%c",Pop(s));
}
Pop(s);
}
}
while(s.base!=s.top) printf("%c",Pop(s));
}