声明:大部分内容来自 - 《2019天勤数据结构高分笔记》
1. 栈
1.1 算术表达式中括号是否匹配,括号只有小括号
完整代码:
#include<bits/stdc++.h>
#define max 100
using namespace std;
void match(char s[])
{
int flag = 1, i;
char st[max];
int top = -1;
for(i = 0; s[i] != '\0'; i++)
{
if(s[i] == '(')
st[++top] = '(';
if(s[i] == ')')
{
if(top == -1)
{
flag = 0;
break;
}
else
{
top--;
}
}
}
if(flag == 1)
cout << "括号匹配" << endl << endl;
else
cout << "括号不匹配!" << endl << endl;
}
int main()
{
char s[max];
while(scanf("%s",s)!=EOF)
match(s);
return 0;
}
1.2 设计算法,求后缀表达式的数值,数值均为一位数,且为整数
完整代码:
#include<bits/stdc++.h>
#define max 100
using namespace std;
int op(int a, int b, char c)
{
if(c == '+')
return a + b;
else if(c == '-')
return a - b;
else if (c == '*')
return a*b;
else if(c == '/' )
{
if(b == 0)
{
cout << "除以0错误!" << endl;
return 0;
}
else
return a/b;
}
}
void com(char s[])
{
int st[max];
int top = -1, i;
int a, b, c;
for(i = 0; s[i] != '\0'; i++)
{
if(s[i] >= '0' && s[i] <= '9')
st[++top] = s[i] - '0';
else
{
b = st[top--];
a = st[top--];
st[++top] = op(a, b, s[i]);
}
}
cout << st[top] << endl << endl;
}
int main()
{
char s[max];
while(scanf("%s", s)!=EOF)
com(s);
}