题解 | 编排字符串

编排字符串

https://www.nowcoder.com/practice/42c0673f04b34f66ae236a1cb7995532

思路:每输入一行字符串进栈st,把st复制一份到stShow,stShow循环4次输出栈顶元素后出栈,若空栈立即退出循环。

#include<stdio.h>
#include<stack>
#include<string>
using namespace std;

int main() {
    //定义一个栈用来保存元素,一个栈用于输出元素
    stack<string> st;
    stack<string> stShow;
    int m;
    string str;
    while (scanf("%d\n", &m) != EOF) {
        char arr[100] = { 0 };
        while (m--) {
            scanf("%s", &arr);
            str = arr;
            st.push(str);//压栈保存
            stShow = st;
            for (int i = 0; i < 4; i++) {
                if (stShow.empty())break;
                printf("%d=%s ", i + 1, stShow.top().c_str());
                stShow.pop();
            }
            printf("\n");
        }
    }
    return 0;
}

计算机复试机试(王道版) 文章被收录于专栏

收录王道2026年计算机复试机试的(课程)代码题解,仅供个人学习参考

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务