• 10.字符串的逆转


    题目: 输入1个英文句子,反转句子中单词的顺序,单词内字符的顺序不变,句子中单词以空格符隔开,标点符号和普通字母一样处理

    解: 这是字符串的逆转,除了用递归,这里用遍历,然后将节点插入到头节点位置。

    代码:

    #include<iostream>
    #include<string>
    #include<sstream>
    using namespace std;
    
    //可以用链表实现的
    typedef struct  node
    {
        string data;
        struct node* next;
    }LinkNode;
    
    void revers(string line)
    {
        string word;
        istringstream stream(line);
        LinkNode* head=NULL;
        LinkNode* pre=NULL;
        //首先组成链表
        while(stream>>word)
        {
            LinkNode* nodeptr=new LinkNode;
            nodeptr->data=word;
            nodeptr->next=NULL;
            if(head==NULL)
            {
                head=nodeptr;
                pre=nodeptr;
            }
            else
            {
                pre->next=nodeptr;
                pre=nodeptr;
            }
        }
    
        //反转链表
        LinkNode* temp=NULL;
        pre=head;
        head=NULL;
        while(pre!=NULL)
        {
            temp=pre;
            pre=pre->next;
            //准备把temp节点插入到头指针pre去
            temp->next=head;
            head=temp;
        }
    
        //打印逆转的
        pre=head;
        while(pre!=NULL)
        {
            cout<<pre->data<<" ";
            pre=pre->next;
        }
        cout<<endl;
    }
    
    int main(void)
    {
        string line;
    
        while(getline(cin,line))
            revers(line);
    
        return 0;
    }
  • 相关阅读:
    Nubiers to follow
    pp to write
    Reading source code
    build opencv with python support
    add monitor resolution
    Install cv2.so for Anaconda
    axios 上传下载显示进度
    vant 上传图片 图片回显 是base64
    多个时间段 合并
    热部署
  • 原文地址:https://www.cnblogs.com/buxianghe/p/3203069.html
Copyright © 2020-2023  润新知