例题6-4 UVA11988 Broken Keyboard(20行AC代码)

紫书刷题进行中,题解系列【GitHub|CSDN

例题6-4 UVA11988 Broken Keyboard(20行AC代码)

题目大意

给定字符串,当输入[时,光标移动到首,当输入]时,光标移动到尾,给出移动后的字符串

思路分析

链表的插入模拟,list可轻松实现,详见代码注释

若想手动实现,静态链表和动态链表均可,注意开头和结尾的处理

AC代码(C++11,list)

#include<bits/stdc++.h>
using namespace std;
string s;
int main() {
    while (cin >>s) {
        list<char> l;
        auto p = l.begin(); // 初始化
        for (auto ch : s) {
            if (ch == '[') p = l.begin(); // 开头
            else if (ch == ']') p = l.end(); // 结尾
            else {
                p = l.insert(p, ch); // 返回插入数据的迭代器
                p ++; // 后移一位
            }
        }
        for (auto ch : l) cout <<ch; // 输出
        puts("");
    }
    return 0;
}
发布了128 篇原创文章 · 获赞 87 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40738840/article/details/104286167
今日推荐