算法提高 逆序排列

问题描述
  编写一个程序,读入一组整数(不超过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
 
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cmath>
 5 #include <stack> 
 6 using namespace std;
 7 int main()
 8 {
 9     int n;
10     stack<int> s;
11     while(cin>>n&&n!=0){
12         s.push(n);
13     }
14     while(!s.empty()){
15         cout<<s.top()<<" ";
16         s.pop();
17     }
18     return 0;
19 }
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cmath>
 5 using namespace std;
 6 int a[30];
 7 int main()
 8 {
 9     int n;
10     int i=0;
11     while(cin>>n&&n!=0){
12         a[i++]=n;
13     }
14     for(int j=i-1;j>=0;j--){
15         if(j==0) cout<<a[j]<<endl;
16         else cout<<a[j]<<" ";
17     }
18     return 0;
19 }

 

posted @ 2019-02-27 15:12  wydxry  阅读(564)  评论(0)    收藏  举报
Live2D