// list.cpp : 定义控制台应用程序的入口点。
//#include "stdafx.h"#include "string"#include "iostream"using namespace std;//申明结构体变量,链表中每个结构体包括单词部分,与链接指针部分
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;//读入字符串,并将有效单词存入链表节点中,链表中单词以原字符串的反向顺序保存有效单词
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; } }
//判断字符串是否为空
if (Current == head) { cout<<"This is a sentence with no words!"<
//反向输出链表里的单词
else { while (Current != head) { cout << Current->word << " "; Current = Current->pre; } cout << endl; }
return 0;
}