由一道题看栈的应用

来源:互联网 发布:微信公众号回调域名 编辑:程序博客网 时间:2024/06/16 03:05

题目:(题目来自华为机试题)

将一个英文语句以单词为单位逆序排放。例如输入“I am a boy”,逆序排放后输出为“boy a am I”
所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符

1.栈的元素是字符

#include <iostream>#include <string>#include <stack>using namespace std;int main()    {    string str1;    getline(cin,str1);    <span style="color:#ff0000;">stack<char> st;</span>    for(int i=str1.size()-1;i>=0;i--)        {         if(str1[i]==' ')        {            while(!st.empty())            {                <span style="color:#ff0000;">cout<<st.top();                </span>st.pop();            }             cout<<' ';             continue;         }        <span style="color:#ff0000;"> st.push(str1[i]);</span>        }       while(!st.empty())            {                cout<<st.top();                st.pop();            }        return 0;}

2.栈的元素是字符串

难点:如何截取一个单词压栈

#include <iostream>#include <string>#include <stack>using namespace std;int main()    {    string str1;    getline(cin,str1);        stack<string> st;    int i,j;    for(i=0;i<str1.size();i++)    {    if(str1[i]==' ')     i++;                 j=i;    while(str1[j]!='\0'&&str1[j]!=' ')    j++;    string word;    word.assign(str1.begin()+i,str1.begin()+j);   //关键,如何截取一个单词压栈;     st.push(word);    i=j;  //改变了i的值,使得本次循环i=j;下次循环i++,即j++,下个单词开始; }     //打印栈st的内容;        while(!st.empty())            {                cout<<st.top()<<" ";                st.pop();            }        return 0;}


0 0
原创粉丝点击