recursion for reverse a sentence by linked list
Dec 4, 2013 at 7:14pm UTC
This program is to print a sentence in an opposite way by putting the world into a linked list one by one.
For the print(),it is required to use recursion rather than while-loop but I do not know how to implement recursion as well as the linked list.
Anyone could help?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#include <iostream>
#include <string>
using namespace std;
class word
{
public :
void print()
{
word *cc;
cc = this ;
do
{
for (int i=0;cc->thisw[i]!='\n' ;i++)
cout<<cc->thisw[i];
cout<<" " ;
cc = cc->pre;
}while (cc);
}
word()
{
next = 0;
pre = 0;
}
word* next; //
word* pre;
char thisw[100];
};
int main()
{
char s;
char stop = '.' ;
int count=0;
int isz=1;
word *my = new word; //save pointer in my
while ((s=getchar())!='\n' )
//to check if stop by checking if there is a full stop
{
if (s=='.' )
{
my->thisw[count] = '\n' ; //
my->next = 0;
break ;
}
isz = 0;
if (s!=' ' )
{
my->thisw[count] = s; //
count = count+1;
}
else
{
my->thisw[count] = '\n' ;
count = 0;
my->next = new word;
my->next->pre = my;
my = my->next;
}
}
my->thisw[count] = '\n' ;
if (!isz)
{
cout<<"The list is:" <<endl;
my->print();
}
return 0;
}
Last edited on Dec 4, 2013 at 7:34pm UTC
Topic archived. No new replies allowed.