后缀表达式
对逆波兰式(即后缀表达式)求值。其中每个操作数的取值范围为0~9,均为个位数。运算符为加减乘除四种(+、-、*、/)。如(4+5)*2-3的逆波兰式为45+2*3-。
输入说明:
一个字符串表示的逆波兰式,如:45+2*3-,表达式的长度不超过100。表达式均没有错误。
#include <stack>
#include <iostream>
using namespace std;
int main()
{//碰到操作数则入栈,碰到操作符则连续两次出栈,然后进行计算。
stack<char> mystack;
int i;
int x,y;
char list[100]={0};
gets(list);
for(i=0;list[i];i++)
{
if(list[i]>='0'&&list[i]<='9')
mystack.push(list[i]);
else
{
y=mystack.top()-'0';mystack.pop();
x=mystack.top()-'0';mystack.pop();
if(list[i]=='+') x=x+y;
else if(list[i]=='-') x=x-y;
else if(list[i]=='*') x=x*y;
else x=x/y;
mystack.push(x+'0');
}
}
x=mystack.top()-'0';
printf("%d",x);
return 1;
}
前缀表达式
对前缀表达式求值,其中操作数为正整数,运算符只包含+-*/,运算结果也为整数。如(42+8)*(36-6)+9/3的前缀表达式为:+ * + 42 8 – 36 6 / 9 3。
输入说明:
输入为一行,一个字符串表示的前缀表达式,如:+ * + 42 8 – 36 6 / 9 3,表达式的长度不超过100,式中不同元素之间用空格隔开。
这个80分没有满分。
//从右到左倒过来处理字符串
//碰到操作数则入栈,碰到操作符则连续两次出栈
//思路:反正从来没有存储操作符就不入了。
//难点:数字范围是0~100,有空格
#include <stack>
#include <iostream>
using namespace std;
int main()
{
stack<int> mystack;
int x,y,i;
int len;
char list[110]={0};
gets(list);
for(x=0;list[x];x++) ;
len=x-1;
for(i=len;i>=0;i--)
{
if(list[i]==' ')
continue;
else if(list[i]>='0'&&list[i]<='9')
{
if(list[i-1]>='0'&&list[i-1]<='9')
{
x=list[i-1]-'0';
y=list[i]-'0';
x=10*x+y;
mystack.push(x);
i--;
}
else
{ x=list[i]-'0';mystack.push(x);}
}
else
{
x=mystack.top();mystack.pop();
y=mystack.top();mystack.pop();
if(list[i]=='+') x=x+y;
else if(list[i]=='-') x=x-y;
else if(list[i]=='*') x=x*y;
else x=x/y;
mystack.push(x);
}
}
//print
x=mystack.top();
printf("%d",x);
return 1;
}
推荐看这一篇。XDOJ 308 前缀表达式求值_immortal5655的博客-CSDN博客
括号匹配
描述:
假设一个表达式或一段程序中含有三种括号:圆括号“(”和“)”、方括号“[”和“]”、花括号“{”和“}”。试写一个程序判别给定的表达式或程序中所含括号是否正确配对出现。
输入说明:
每行为一个含有括号的表达式或一段程序。
输出说明:
输出一个right或wrong,表明正确匹配与否。
/*
思路:左括号入栈,右括号检验出栈。
失败:栈非空||左右不匹配
*/
#include<stack>
#include<iostream>
using namespace std;
int main()
{
stack<char>stack;
char list[100]={0};
gets(list);
int i;
for(i=0;list[i];i++)
{
if(list[i]=='('||list[i]=='['||list[i]=='{')
stack.push(list[i]);//左括号入栈
else if(list[i]==')'||list[i]=='}'||list[i]==']')
{//右括号出栈
if(stack.size()==0)
{
printf("wrong");
return 1;
}
if(list[i]==')')
{
if(stack.top()=='(')//无事发生
stack.pop();
else
{
printf("wrong");
return 1;
}
}
else if(list[i]==']')
{
if(stack.top()=='[')//无事发生
stack.pop();
else
{
printf("wrong");
return 1;
}
}
else
{
if(stack.top()=='{')//无事发生
stack.pop();
else
{
printf("wrong");
return 1;
}
}
}
else continue;
}
if(stack.size())
printf("wrong");
else
printf("right");
return 1;
}