利用数组模拟栈,实现逆序输出。

文章展示了如何在C++中利用STL库的stack容器和数组来实现逆序输出字符串。首先,通过STLstack的例子解释了如何读入输入并将其存储到栈中,然后逆序打印。接着,讨论了如何用数组模拟栈,分别展示了top初始化为-1和0的两种情况,同样达到逆序输出的效果。
摘要由CSDN通过智能技术生成

【利用STL stack实现逆序输出的代码】
在算法竞赛中,利用STL stack实现逆序输出,特别好理解。
STL stack的官方帮助文档详见:https://cplusplus.com/reference/stack/stack/

下面,给出一个利用STL stack实现逆序输出的代码。如下所示:

#include <bits/stdc++.h>
using namespace std;
 
int n;
char x;
int main() {
    cin>>n;
    stack<char> s;
 
    while(n--) {
        cin>>x;
        s.push(x);
    }
 
    while(!s.empty()) {
        cout<<s.top();
        s.pop();
    }
 
    return 0;
}
 
 
/*
in:
5
abcde

out:
edcba
*/

针对上面实例,在实践中,也常有利用数组模拟栈实现的需求。据此,根据栈的特点,引入整型变量top表示栈顶,引入了字符数组s[]表示栈(假定本例中数组中的元素个数最多不超过100个,也即用数组模拟的栈中的元素个数不超过100个)。根据top初始取0或-1的不同,下面分别给出了利用数组模拟栈的代码。

【top初始取-1时,用数组模拟栈实现逆序输出的代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=105;
char s[maxn];

int main() {
    char x;
    int top=-1;
    
    int n;
    cin>>n;
    while(n--) {
        cin>>x;
        s[++top]=x;
    }

    while(top!=-1) {
        cout<<s[top];
        top--;
    }

    return 0;
}


/*
in:
5
abcde

out:
edcba
*/

【top初始取0时,用数组模拟栈实现逆序输出的代码】

#include <bits/stdc++.h>
using namespace std;

const int maxn=105;
char s[maxn];

int main() {
    char x;
    int top=0;
    
    int n;
    cin>>n;
    while(n--) {
        cin>>x;
        s[++top]=x;
    }

    while(top!=0) {
        cout<<s[top];
        top--;
    }

    return 0;
}


/*
in:
5
abcde

out:
edcba
*/


【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/120588993


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值