用栈实现自定义算术运算
对应运算:
@ +
# -
$ *
& /
且有规则 2@3$4=2*(3$4)。
实现要点:
1)定义数字栈和符号栈;
2)压栈操作是栈顶指针先加1,再赋值,出栈操作时先赋值,栈顶指针再减1;
3)用switch语句实现算术运算和优先规则定义要简单些;
4)主函数中,对每个数字进行数字栈入栈操作,根据运算符的优先级,对符号栈分别进行入栈(后一个运算符的优先级比前一个高),出栈(优先级相等),计算后入栈(后一个运算符的优先级比前一个低)。注意,只有在符号入栈和出栈操作时(前两种情况)才对向后移动指针,如果不这样会导致第三种情况计算后符号栈中低优先级的运算不会进行。
#include<iostream>
using namespace std;
typedef struct _num_stack
{
int data[100];
int size;
int top;
}num_stack;
typedef struct _char_stack
{
char sym[100];
int size;
int top;
}char_stack;
void init(num_stack *&num_s,int size_num,char_stack *&char_s,int size_char)
{
num_s=(num_stack *)malloc(sizeof(num_stack));
if(num_s==NULL)
return ;
num_s->top=-1;
num_s->size=100;
char_s=(char_stack *)malloc(sizeof(char_stack));
if(char_s==NULL)
return ;
char_s->top=-1;
char_s->size=100;
}
void num_push(num_stack *head,int key)
{
// cout<<"num_push"<<endl;
if(head->top==head->size)
return;
head->top++;
cout<<"数字压栈 "<<head->top<<" "<<key<<endl;
head->data[head->top]=key;
}
void num_pop(num_stack *head,int *key)
{
if(head->top==-1)
return;
*key=head->data[head->top];
head->top--;
}
void char_push(char_stack *head,char c)
{
if(head->top==head->size)
return;
head->top++;
head->sym[head->top]=c;
cout<<"运算符压栈 "<<head->top<<" "<<c<<endl;
}
void char_pop(char_stack *head,char *c)
{
if(head->top==-1)
return;
*c=head->sym[head->top];
head->top--;
}
int operate(int i,char c,int j)
{
int result;
switch(c)
{
case '@':
result=i+j;
break;
case '#':
result=i-j;
break;
case '$':
result=i*j;
break;
case '&':
result=i/j;
break;
}
return result;
}
char precede(char s,char t)
{
char tmp;
switch(s)
{
case '@':
if(t=='$')
tmp='<';
else
tmp='>';
break;
case '#':
case '&':
case '$':
tmp='>';
break;
case '+':
if(t=='+')
tmp='=';
else
tmp='<';
}
// cout<<tmp<<endl;
return tmp;
}
char gettopchar(char_stack *my)
{
return my->sym[my->top];
}
int gettopnum(num_stack *my)
{
return my->data[my->top];
}
int main()
{
num_stack *my_num_stack;
char_stack *my_char_stack;
char string[100];
char *p,theta;
int i,j,tmp,result;
tmp=0;
init(my_num_stack,100,my_char_stack,100);
char_push(my_char_stack,'+');
gets(string);
p=string;
while(*p)
{
tmp=0;
if((*p-'0')>=0&&(*p-'0')<10)
{
while(*p-'0'>=0&&*p-'0'<10)
{
tmp=tmp*10+(*p-'0');
p++;
}
// cout<<tmp<<endl;
num_push(my_num_stack,tmp);
}
else
{
switch(precede(gettopchar(my_char_stack),*p))
{
case '<':
char_push(my_char_stack,*p);
p++;
break;
case '=':
char_pop(my_char_stack,&theta);
p++;
break;
case '>':
char_pop(my_char_stack,&theta);
num_pop(my_num_stack,&j);
num_pop(my_num_stack,&i);
cout<<"运算 "<<i<<" "<<theta<<" "<<j<<endl;
result=operate(i,theta,j);
num_push(my_num_stack,result);
break;
}
}
}
cout<<gettopnum(my_num_stack)<<endl;
return 1;
}