题目:DS 堆栈–行编辑
Description:
使用 C++的 STL 堆栈对象,编写程序实现行编辑功能。行编辑功能是:当输入#字
符,则执行退格操作;如果无字符可退就不操作,不会报错
本程序默认不会显示#字符,所以连续输入多个#表示连续执行多次退格操作
每输入一行字符打回车则表示字符串结束
注意:必须使用堆栈实现,而且结果必须是正序输出
Input:
第一行输入一个整数 t,表示有 t 行字符串要输入
第二行起输入一行字符串,共输入 t 行
Output:
每行输出最终处理后的结果,如果一行输入的字符串经过处理后没有字符输出,则直接输出 NULL
Sample Input:
5
Chinaaa##
Guu#a#angDong
##Shen###Zhen###
sb#zz#tu
IoT###
Sample Output:
China
GuangDong
SZ
sztu
NULL
示例图:

Reference code:
#include<iostream>
#include<stack>//新的头文件<stack>
#include<cstring>
using namespace std;
int main()
{
int t;
string str;
int len = 0;
cin >> t;
while (t--)
{
cin >> str;
len = str.length();//length()包含在<cstring>头文件里,直接用就行,取长度
stack<char>s;//定义堆栈s
for (int i = 0; i < len; i++)
{
if (str[i] != '#')//不是退格操作,直接压栈
{
s.push(str[i]);
}
else if (str[i] == '#' && s.empty() == false)//是退格但栈非空
{
s.pop();//出栈
}
else//(str[i] == '#' && s.empty() == true) 是退格但栈已空
{
}
}
if (s.empty() == true)//经过上面的进栈出栈后,栈是空的
{
cout << "NULL" << endl;
}
else
{
//因为题目要求正序输出,所以要新建一个栈,把旧栈的元素压进新栈,在用新栈来正常输出就是正序了
stack<char>news;
while (s.empty() == false)
{
news.push(s.top());//将旧栈的最上面的元素压进新栈
s.pop();//弹出旧栈的最上面的元素
}
while (news.empty() == false)
{
cout << news.top();
news.pop();
}
cout << endl;
}
}
return 0;
}
C++实现DS堆栈行编辑功能
1429

被折叠的 条评论
为什么被折叠?



