前言:运用栈对后缀表达式求值比较简单,在日常应用中有必要将中缀表达式转换为后缀表达式来处理。
代码展示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include<iostream>
using namespace std;
struct stacknode
{
int top;
char data[100];
};
struct stacknode1
{
int top;
int data[100];
};
typedef stacknode *stack;
typedef stacknode1 *nstack;
int priority(char);
void pop(stack);
int pop1(nstack s);
char top(stack);
int top1(nstack s);
void push(stack,char);
void push1(nstack,char);
void push2(nstack s,int c);
bool isnumber(char);
bool isempty(stack);
int main()
{
int i,j,len,count=0;
stack s=new stacknode;
nstack result=new stacknode1;
char instr[100];
char outstr[100];
cout<<"please input the test:";
scanf("%s",instr);
len=strlen(instr);
s->top=-1;
result->top=-1;
for(int i=0;i<len;i++)
{
if(isnumber(instr[i]))
outstr[count++]=instr[i];
else
{
if(instr[i]=='('||isempty(s))
{
push(s,instr[i]);
continue;
}
if(instr[i]==')')
{
while(top(s)!='(')
{
outstr[count++]=top(s);
pop(s);
}
pop(s);
continue;
}
while(!isempty(s)&&top(s)!='('&&priority(instr[i])<=priority(top(s)))
{
outstr[count++]=top(s);
pop(s);
}
push(s,instr[i]);
}
}
while(!isempty(s))
{
outstr[count++]=top(s);
pop(s);
}
outstr[count]='\0';
for(int i=0;i<count;i++)
{
printf("%c ",outstr[i]);
}
cout<<endl;
int a=0,b=0;
for(int i=0;i<count;i++)
{
if(isnumber(outstr[i]))
{
push1(result,outstr[i]);
}
else if(outstr[i]=='+')
{
a=pop1(result);
b=pop1(result);
push2(result,b+a);
}
else if(outstr[i]=='-')
{
a=pop1(result);
b=pop1(result);
push2(result,b-a);
}
else if(outstr[i]=='*')
{
a=pop1(result);
b=pop1(result);
push2(result,b*a);
}
else if(outstr[i]=='/')
{
a=pop1(result);
b=pop1(result);
push2(result,b/a);
}
}
printf("the test result is:%d",top1(result));
}
bool isnumber(char c)
{
if(c>='0'&&c<='9')
return true;
else
return false;
}
bool isempty(stack s)
{
if(s->top==-1)
return true;
else
return false;
}
int priority(char c)
{
if(c=='(')
return 0;
if(c=='+'||c=='-')
return 1;
if(c=='*'||c=='/')
return 2;
return 0;
}
void push(stack s,char c)
{
s->data[++s->top]=c;
}
void push1(nstack s,char c)
{
s->data[++s->top]=c-'0';
}
void push2(nstack s,int c)
{
s->data[++s->top]=c;
}
char top(stack s)
{
return s->data[s->top];
}
int top1(nstack s)
{
return s->data[s->top];
}
int pop1(nstack s)
{
return s->data[s->top--];
}
void pop(stack s)
{
s->top--;
}