[英]Reverse words in a sentence in c++ using stack
输入
“天是蓝的”
预期产出
“蓝色是天空”
我的输出
“蓝色是天空”
我无法指出代码中的错误。
这是代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "the sky is blue";
reverse(s.begin(),s.end());
stack<char> t;
for(int i = 0;i < s.length();i++){
if(s[i] != ' '){
t.push(s[i]);
}
else{
while(!t.empty()){
cout << t.top();
t.pop();
}
cout << " ";
}
}
return 0;
}
您将“eht”推入堆栈,但您没有开始弹出它,因为字符串的长度不允许您这样做,因为 for 循环停止执行。
在 for 循环之后弹出它,如下所示:
#include <string>
#include <stack>
#include <algorithm>
#include <iostream>
using namespace std;
int main(){
string s = "the sky is blue";
reverse(s.begin(),s.end());
stack<char> t;
for(unsigned int i = 0;i < s.length();i++){
if(s[i] != ' '){
t.push(s[i]);
}
else {
while(!t.empty()){
cout << t.top();
t.pop();
}
cout << " ";
}
}
while(!t.empty()){
cout << t.top();
t.pop();
}
}
输出:
蓝色是天空
C++ 程序使用堆栈数据结构反转字符串中的单词。
例如,“my.name.is.vivek.mutha”给出的输出为“mutha.vivek.is.name.my”。
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s,s1;
std::stack<std::string> st;
int k=0;
cin>>s;
int l = s.length();
vector<string> str;
for(int i=0;i<l;i++)
{
if(s[i]=='.'){
str.push_back(s1);
str.push_back(".");
s1="";
}
else
s1.append(s,i,1);
}
str.push_back(s1);
for(int i=0;i<str.size();i++)
st.push(str[i]);
while(!st.empty()){
cout<<st.top();
st.pop();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.