以链表方式实现字符串中的单词顺序反转

// list.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "string"
#include "iostream"
using namespace std;ios

//申明结构体变量,链表中每一个结构体包括单词部分,与连接指针部分
spa

struct wordElem
{
    string word;
    wordElem  *pre;
};

int _tmain(int argc, _TCHAR* argv[])
{
   //因为cin不能读入空格或换行等字符,故在读入前需先作以下语句的申明
指针

 cin.unsetf(ios::skipws);

    char input;
    string word;
    string blanks;
    wordElem *head;
    wordElem *Current;
    wordElem *tempElem;
    head = new wordElem;
    head->pre = NULL;
    Current = head;
    cout<<"Please input a string"<<endl;
    cin>>input;
code

//读入字符串,并将有效单词存入链表节点中,链表中单词以原字符串的反向顺序保存有效单词
ip

    while (input!= '\n')
    {
        //读入有效单词存储在word变量中
        while ((input >= 'a'&&input <= 'z') || (input >= 'A'&&input <= 'Z') || (input >= '0'&&input<= '9'))
        {
            word += input;
            cin>>input;
            if (input == '\n')
            {
                break;
            }
        }
        //将有效单词存入链表节点中
        if (word.length() > 0)
        {
            tempElem = new wordElem;
            tempElem->word = word;
            tempElem->pre = Current;
            Current = tempElem;
            word.clear();
        }
        //读入分隔符,如空格符或标点符号,忽视分隔符
        while (input!='\n' &&!((input >= 'a'&&input <= 'z') || (input >= 'A'&&input <= 'Z') || (input >= '0'&&input<= '9')))
        {
            blanks += input;
            cin>>input;
        }
    }

//判断字符串是否为空
ci

    if (Current == head)
    {
        cout<<"This is a sentence with no words!"<<endl;
    }

  //反向输出链表里的单词
字符串

  else
    {
        while (Current != head)
        {
            cout << Current->word << " ";
            Current = Current->pre;
            
        }
        cout << endl;
        
    }

    return 0;
}


input

相关文章
相关标签/搜索