题目描述:一行内输入一串整数,以0结束,以空格间隔。一行内倒着输出这一串整数,以空格间隔。
分析:输入规模较小,主要试试递归和模拟栈。
代码:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<vector>
#define ll long long
using namespace std;
#define inf 0x3f3f3f3f
int n;
void fun()
{
int a;
scanf("%d",&a);
if (a == 0) //结束条件
return ;
fun();
printf("%d ", a); //递归返回时完成输出即可实现后进先出
}
int main()
{
int i, j;
while(~scanf("%d", &n))
{
fun();
printf("%d\n",n);
}
return 0;
}
#include<cstdio>
#include<iostream>
using namespace std;
#define inf 0x3f3f3f3f
int n;
int sta[110];
int main()
{
int i, top = 0;
do
{
scanf("%d", &sta[top ++]);
}while(sta[top - 1]); //总是指向下一个还未输入的位置
top -= 2; //减一后指向0, 再减一
while(top)
{
printf("%d ", sta[top --]);
}
printf("%d\n", sta[top]);
return 0;
}
网友评论