蓝桥杯 算法提高 逆序排列

问题描述
  编写一个程序,读入一组整数(不超过20个),并把它们保存在一个整型数组中。当用户输入0时,表示输入结束。然后程序将把这个数组中的值按逆序重新存放,并打印出来。例如:假设用户输入了一组数据:7 19 -5 6 2 0,那么程序将会把前五个有效数据保存在一个数组中,即7 19 -5 6 2,然后把这个数组中的值按逆序重新存放,即变成了2 6 -5 19 7,然后把它们打印出来。
  输入格式:输入只有一行,由若干个整数组成,中间用空格隔开,最末尾的整数为0。
  输出格式:输出也只有一行,即逆序排列后的整数,中间用空格隔开,末尾没有空格。
  输入输出样例
样例输入
7 19 -5 6 2 0
样例输出

2 6 -5 19 7

本题目方法多样,你既可以用数组,也可以用递归来做,还可以用容器来做。数组倒序输出就行了,容器用vector的反向迭代器也很容易.

vector做法:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
 vector<int > s;
 int k;
 while(1)
 {
  cin >> k;
  if (k != 0)
  {
   s.push_back(k);
  }
  else
   break;
 }
 vector<int >::reverse_iterator it = s.rbegin();
 while (it != s.rend())
 {
  cout << (*it) << " ";
  it++;
 }
 system("pause");
 return 0;
}

递归做法:

#include <iostream>
using namespace std;
void dfs(int n);
int main()
{
 dfs(12);
 cout << endl;
 return 0;
}
void dfs(int n)
{
 if (n == 0)
  return;
 else
 {
  cin >> n;
  dfs(n);
  if (n != 0)
  {
   cout << n << " ";
  }
 }
}

数组做法:

#include <stdio.h>
int main()
{
 int a[40];
 int i = 0;
 while (1)
 {
  scanf("%d",&a[i]);
  if (a[i] == 0)
  {
   i--;
   break;
  }
  else
   i++;
 }
 while (i >= 0)
 {
  printf("%d ",a[i]);
  i--;
 }
 printf("\n");
}

你可能感兴趣的:(蓝桥杯,逆序输出)