A - 数据结构实验之栈与队列一:进制转换
Description
输入一个十进制非负整数,将其转换成对应的 R (2 <= R <= 9) 进制数,并输出。
Input
第一行输入需要转换的十进制非负整数;
第二行输入 R。
Output
输出转换所得的 R 进制数。
Sample
Input
1279
8
Output
2377
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,r,top;
int a[10010];
scanf("%d",&n);
scanf("%d",&r);
top=0;
if(n==0)
{
printf("%d\n",n);
}
else
{
while(n)
{
a[top]=n%r;
n=n/r;
top++;
}
for(int i=top-1; i>=0; i--)
{
printf("%d",a[i]);
}
printf("\n");
}
return 0;
}
B - 数据结构实验之栈与队列二:一般算术表达式转换成后缀式
Description
对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。
Input
输入一个算术表达式,以‘#’字符作为结束标志。
Output
输出该表达式转换所得到的后缀式。
Sample
Input
a*b+(c-d/e)*f#
Output
ab*cde/-f*+
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int st(char a)
{
if(a=='+'||a=='-') return 1;
else if(a=='/'||a=='*') return 2;
else if(a=='(') return 3;
else if(a==')') return 4;
return 0;
}
int main()
{
int top=0;
char s,b[1000010];
while(~scanf("%c",&s)&&s!='#')
{
if(s>='a'&&s<='z')
{
printf("%c",s);
}
else
{
if(top==0)
{
top++;
b[top]=s;
}
else if(st(s)>st(b[top]))
{
if(st(s)==4)
{
while(b[top]!='(')
{
printf("%c",b[top]);
top--;
}
top--;
}
else
{
top++;
b[top]=s;
}
}
else
{
if(b[top]=='(')
{
top++;
b[top]=s;
}
else
{
printf("%c",b[top]);
b[top]=s;
}
}
}
}
while(top)
{
printf("%c",b[top]);
top--;
}
printf("\n");
return 0;
}
C - 数据结构实验之栈与队列三:后缀式求值
Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Sample
Input
59*684/-3*+#
Output
57
Hint
基本操作数都是一位正整数!
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[1000001];
int x,y,top,i,j,k,m,n;
char b[1000001];
scanf("%s",b);
n=strlen(b);
top=0;
for(i=0;i<n;i++)
{
if(b[i]=='#')
{
break;
}
else
{
if(b[i]>='0'&&b[i]<='9')
{
a[top]=b[i]-'0';
top++;
}
else if(b[i]=='*')
{
a[top-2]=a[top-1]*a[top-2];
top--;
}
else if(b[i]=='-')
{
a[top-2]=a[top-2]-a[top-1];
top--;
}
else if(b[i]=='+')
{
a[top-2]=a[top-2]+a[top-1];
top--;
}
else if(b[i]=='/')
{
a[top-2]=a[top-2]/a[top-1];
top--;
}
}
}
printf("%d\n",a[0]);
return 0;
}
D - 数据结构实验之栈与队列四:括号匹配
Description
给你一串字符,不超过50个字符,可能包括括号、数字、字母、标点符号、空格,你的任务是检查这一串字符中的( ) ,[ ],{ }是否匹配。
Input
输入数据有多组,处理到文件结束。
Output
如果匹配就输出“yes”,不匹配输出“no”
Sample
Input
sin(20+10)
{[}]
Output
yes
no
#include <bits/stdc++.h>
using namespace std;
char d[55];
char a[55];
int main()
{
int n,i;
while(gets(a)!=NULL)
{
int flag=0,top=-1;
n=strlen(a);
for(i=0; i<n; i++)
{
if(a[i]=='('||a[i]=='['||a[i]=='{')
{
d[++top]=a[i];
}
else
{
if(a[i]==')')
{
if(top!=-1&&d[top]=='(')
{
top--;
}
else
{
flag=1;
break;
}
}
if(a[i]==']')
{
if(top!=-1&&d[top]=='[')
{
top--;
}
else
{
flag=1;
break;