以鏈表方式實現字符串中的單詞順序反轉

// 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

相關文章
相關標籤/搜索