?
Solved

linked list sorting

Posted on 2003-03-26
39
Medium Priority
?
332 Views
Last Modified: 2013-12-14
I have this code whereby i have a linked list and i read in a string from a file and store the contents and print each word in the sentence out indivually,
the problem is that i have a function to sort a list of words alphabetically but cannot get this to sort the sentence in the list alphabetically before it's printed out
the function to sort is completely seperate to the list,

this is what i have so far;


#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std;


struct node                                   // struct of item in list
{
     string str;                              // the sring to be entered
     node   *next;                         // the next item in the list
};



class List
{
private:
     node *data;                              // the data of an item
public:
     List(): data(NULL){};
     List(string item);
     ~List();
     void add(string item);               // adding item to list
     void printout();                    // printing items
     int sort();
};



List::List(string item)
{
     node *newnode = new node;          // add first node
     newnode->str = item;
     newnode->next = NULL;
     data = newnode;
}



List::~List()
{
     node *i;
     node *temp=this->data;
     
     for(i=this->data->next; i->next != NULL; i = i->next)
     {
          delete temp;
          temp = i;
     }  
}



void List::add(string item)
{
     
     if (data == NULL)                         // if list is empty
     {
          node *newnode = new node;          // add first node
          newnode->str = item;
          newnode->next = NULL;
          data = newnode;
     }
     
     else
     {
           
          node *i;                              // get to the end of list
         
          for(i=this->data; i->next != NULL; i = i->next);
         
          node *newnode = new node;          // insert new item
          newnode->str = item;
          newnode->next = NULL;
          i->next = newnode;
     }
}



void List::printout()
{
     node *i=this->data;

     for( i=this->data; i != NULL; i=i->next )
          cout << "\t" << i->str << endl;
}



int List::sort()
{
     const int SIZE = 80;

     char text[3][SIZE], *temp, words[100][20]={""};

     int count[100]={0};
     
     cout << "\nEnter the sentence as shown above (case senstive); \n" << endl;

     for ( int i = 0; i <= 2; i++ )
          cin.getline ( &text [i][0], SIZE );
     
     for ( i = 0; i <= 2; i++ )
     
     {
          temp = strtok( &text [i][0], ". \n" );
               
          while (temp)
          {
               for ( int j = 0; words[j][0] && strcmp(temp, &words[j][0]) != 0; j++ );  
               ++count[j];
                   
               if ( !words [j][0] )
                    strcpy( &words [j][0], temp );
                   
               temp = strtok( NULL, ". \n" );
          }
     }
     
     cout.put( '\n' );

     cout<<" Word "<<"\t"<<"   Times found"<< "\t" << " File" <<endl;
     cout<<"________________________________"<<endl;

     for ( int j = 0; words [j][0] != '\0' && j <= 99; j++ )
     {
          cout << " " << &words[j][0] << "\t\t" << count[j] << "\t" << "test.txt"<<endl;    
     }

     cout<<"________________________________"<<endl;

     return 0;

}          




int main()
{
     List *words = new List();

     ifstream in("test.txt");  
     string word;
   
     while(in >> word)               // word is detected by white space
          words->add(word);

     cout<<"\n Words from file in order."<<endl;
     cout<<"____________________________\n"<<endl;

     words->printout();

     cout<<" \n "<<endl;

     words->sort();

     return 0;
}

thanks in advance for any help
0
Comment
Question by:PALKTA
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 16
  • 9
  • 5
  • +3
39 Comments
 
LVL 4

Expert Comment

by:n_fortynine
ID: 8215225
If you
>>cannot get this to sort the sentence in the List
>>alphabetically before it's printed out
it's probably because your sort() does not "touch" the elements of the List at all??? Care to explain what you intend to have sort() do?

Otherwise, what is more efficient would be to reimplement add() to add things in sorted order.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8215768
>> Care to explain what you intend to have sort() do?

Good question :-)

Mayank.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8215775
Moreover, the printout () statement is also before the sort (). I guess that sort () is supposed to print something. It looks so terrifying though.... don't think that I have the courage to go through it.

Mayank.
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Expert Comment

by:violent1
ID: 8216017
i'm looking through...i must say, it's not the friendliest sort...but, how many are?

at any rate, to mayankeagle:
printout just prints the words he wants you to type in.  his implementation has it so that the program reads in from a text file, displays the words on the screen, then has the user type in those words for use in his sort apaprently.
0
 

Expert Comment

by:violent1
ID: 8216023
so, basically he isn't sorting the list itself, but creates a bigass array that contains the same words as the list and has the user fill that array.  and then he sorts the array and displays his results...

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8216038
Thanks for going through the trouble of verifying what it does. I guess he'll think of changing it.

Mayank.
0
 

Expert Comment

by:violent1
ID: 8216177
please revise your sort.  i am fairly certain that it doesn't sort at all.  for instance, when you use strcmp you check if it is not equal to zero.  that doesn't help you sense there are 3 cases for strcmp:
< 0 if string1 is lexographically less than string2
0   if string1 is lexographically identical to string2
> 0 if string1 is lexographically greater than string2

by only checking if it is not equal to zero, you don't allow for being able to determine the placement of the word based on it being greater or less than the compared string.

for a reference, here is an example of sorting an array of ints:

int temp;
for(int j=0;j<i;j++)
     for(int k=0;k<i-1;k++)
          if(mitems[k+1] < mitems[k])
          {
               temp = mitems[k];
               mitems[k] = mitems[k+1];
               mitems[k+1] = temp;
          }

i'm sure once you setup the proper control paths you will be able to do the sorting as well.

0
 
LVL 4

Expert Comment

by:n_fortynine
ID: 8216207
probably what PALKTA is trying to do is sort a LL so it'll not be as simple as sorting an array of integers. The best thing to do here is to merge this idea into add(). But I want to hear PALKTA says what he/she *really* wants to do.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8216230
Here's how to sort a linked list that contains strings (as character arrays):

void List :: sort ()
{
  if ( data == NULL )
    return ; // end if

  char line[80] ;
 
  for ( node * temp = data ; temp -> next != NULL ; temp = temp -> next )
    for ( node * ptr = temp -> next ; ptr != NULL ; ptr = ptr -> next )
      if ( strcmpi ( temp -> str, ptr -> str ) > 0 )
      {
        strcpy ( line, temp -> str ) ;
        strcpy ( temp -> str, ptr -> str ) ;
        strcpy ( ptr -> str, line ) ;

      } // end if, fors

  return ;

} // end of sort ()


Mayank.
0
 

Expert Comment

by:violent1
ID: 8216236
>>so it'll not be as simple as sorting an array of integers

well, no.  it's just a basic example of how to sort an array.  i only put it because he didn't sort at all and i thought perhaps he didn't understand the concept.  the concept of the sorting an array of int vs array of char is still the same.  the only difference is what you use to compare.

0
 

Expert Comment

by:violent1
ID: 8216243
>>mayankeagle
good job!  the question of course is does he really want to sort the list, or just display a sorted version of the list that he stores in the array.  either way, i think ultimately we are right in assuming his sort function is where the major fault lies.

0
 

Author Comment

by:PALKTA
ID: 8216986
I would like the sort function to sort the list in alphabetical order and then print the list out, sorry about the confussion surrounding this!!!

I relise that the sort function already in my above code does not touch the list but i did this for an experiment.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8217035
You have the required code above in my example.... you need to modify it a little bit for string objects. I hope you can try that!

Mayank.
0
 
LVL 7

Expert Comment

by:a1programmer
ID: 8220002
Try this... ...



void List::sort(){
string tempStr;

for (node* temp = this; temp->next != NULL; temp = temp->next){
    for (node* cursor = this->next; cursor->next != NULL; cursor=cursor->next){
          if (temp->str > cursor->str){
               tempStr = temp->str;
               temp->str = cursor->str;
               cursor->str = tempStr;
          }


   }
}

}
0
 
LVL 7

Expert Comment

by:a1programmer
ID: 8220013
you can use  >=, <= , > , < , == with string object...


Hope the above helps...
0
 
LVL 7

Expert Comment

by:a1programmer
ID: 8220023
Updated Second (for)...  you need to hit the last node... oops.


void List::sort(){
string tempStr;

for (node* temp = this; temp->next != NULL; temp = temp->next){
   for (node* cursor = this->next; cursor != NULL; cursor=cursor->next){
         if (temp->str > cursor->str){
              tempStr = temp->str;
              temp->str = cursor->str;
              cursor->str = tempStr;
         }


  }
}

}
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8222795
a1programmer,

You might be an A1-programmer, but I don't see much of a difference between your code and mine (except for the very small change that your's is for 'string' objects and mine for strings as character arrays. (I agree that it'd be the standard way of applying selection-sort).

Come on, fellows! Let the questioner do something on his own!

Mayank.
0
 

Expert Comment

by:Caio_Proiete
ID: 8224851
Hi Mayank!

FYI, there is a BIG difference between your code and A1Programmer code.

In your SORT, you make a COPY of each string character array on every swap!!!
In the A1Programmer code, he just swap POINTERS!!

The A1Programmer code is much faster!!

cheers,

Caio Proiete




>> a1programmer,
>> 
>> You might be an A1-programmer, but I don't see much of
>> a difference between your code and mine (except for the
>> very small change that your's is for 'string' objects
>> and mine for strings as character arrays. (I agree that
>> it'd be the standard way of applying selection-sort).
>> 
>> Come on, fellows! Let the questioner do something on
>> his own!
>> 
>> Mayank.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8224897
>> he just swap POINTERS

He's swapping objects, not pointers.

>> In your SORT, you make a COPY of each string character array on every swap!!!

Has to be, 'cause I am assuming strings to be implemented as character arrays, not objects of the 'string' class. There''ll be lots of difference in the underlying implementation, but not much in the apparent code.... that's why I said, let the questioner figure out something on his own....

>> The A1Programmer code is much faster!!

But actually, I think that A1's code will also take equal time because he is not swapping pointers, but swapping string objects (the string data-member), in which eventually an equal amount of data has to be moved.

Cheers,

Mayank.
0
 
LVL 7

Expert Comment

by:a1programmer
ID: 8224942
Actually... he's right... I'm not swapping pointers, but I am not swapping objects either...

Reassigning a string basically the exact same thing as strcpy.  Probably takes equal time... (Reassigning string members inside the object)

Swapping pointers may not me much faster anyway... Its still going to require 3 assignments, even though they are memory addresses.  But, if you were dealing with really long strings it probably would...
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8225042
A1programmer,

Swapping pointers would be a good idea though, if the string data-members were character-pointers, allocated memory by 'new'. In our loops, when the strings are copied, all the characters have to be copied, which means that another underlying nested loop is involved. But if we swap pointers to dynamically allocated memory spaces, then there will only 3 assignments, no underlying loops. In my case, I have character-arrays, and so, I cannot swap them.... I have to copy them. But I had pointers, it'd been better. But anyways, since his data is the'string' object and not a character-array or pointer, I think we can drop this topic of discussion....

Cheers,

Mayank.
0
 
LVL 7

Expert Comment

by:a1programmer
ID: 8225086
I was thinking along the lines of reassigning the entire objects...  Since it is a linked list.  

Good Idea...


Is the questioner ever going to respond? lol... ...
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8225129
God knows :-) He did,... once upon a time.... :-)

PALKTA,

Please read all the comments. There are already enough to solve your problem in 3-4 different ways!

Mayank.
0
 

Expert Comment

by:Caio_Proiete
ID: 8226136
Hi Mayank / A1Programmer,

I made a mistake :)... I didn't saw that A1Programmer's code use a STL string...

All I do with linked list is with char *.. it's really much faster than swap the entire string...

Almost all strings are bigger than 4 bytes right?
Swapping pointers only costs 4 bytes...

cheers,

Caio Proiete
0
 

Author Comment

by:PALKTA
ID: 8244480
Hi a1Programmer
Thanks for your sort function but i am getting one error reading

'initializing' : cannot convert from 'class List *const ' to 'struct node *'

this is happening on the FIRST for loop in the function and i cannot get it, would be grateful if you or anyone else could help me on this!!!!
Thanks.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8244539
You cannot assign the address of the object (this) to a structure pointer (temp). You will have to assign the location pointed to by the 'data' pointer-member of the class.

Make these changes:

>> for (node* temp = this; temp->next != NULL; temp = temp->next){
>>    for (node* cursor = this->next; cursor->next != NULL; cursor=cursor->next){

for  ( node * temp = this -> data ; temp -> next != NULL ; temp = temp -> next )
{
  for ( node * cursor = this -> data -> next ; cursor ->next != NULL ; cursor = cursor -> next )
  {
    ..
    ..  
     
Mayank.
0
 

Author Comment

by:PALKTA
ID: 8245597
Mayank

this code compiles and runs for me but i am a bit confused about it's output as it does notgive me a print out of the words in alphabetical order
i would be very grateful if you could sort this
thaks

Palkta
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8250959
There doesn't seem to be anything wrong with it in the first glance. Please post your entire updated code, so that we can see what is happening there. There might be some errors in creation or display or calling itself.

Thanks,

Mayank.
0
 

Author Comment

by:PALKTA
ID: 8254205

Mayank,
My entire code to date, i am wanting to print the sentence from the file out in a list in alphabetical order as is done using the linked list, but that only displays it

Thanks

PALKTA



#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std;


struct node                                          // struct of item in list
{
      string str;                                    // the sring to be entered
      node * next;                              // the next item in the list
};



class List
{
private:
      node *data;                                    // the data of an item
      node *next;
public:
      List(): data(NULL){};
      List(string item);
      ~List();
      void add(string item);                  // adding item to list
      void printout();                        // printing items
      int sort();      
      void sorting();
};



List::List(string item)
{
      node *newnode = new node;            // add first node
      newnode->str = item;
      newnode->next = NULL;
      data = newnode;
}



List::~List()
{
      node *i;
      node *temp=this->data;
      
      for(i=this->data->next; i->next != NULL; i = i->next)
      {
            delete temp;
            temp = i;
      }  
}



void List::add(string item)
{
      
      if (data == NULL)                              // if list is empty
      {
            node *newnode = new node;            // add first node
            newnode->str = item;
            newnode->next = NULL;
            data = newnode;
      }
      
      else
      {
             
            node *i;                                    // get to the end of list
            
            for(i=this->data; i->next != NULL; i = i->next);
            
            node *newnode = new node;            // insert new item
            newnode->str = item;
            newnode->next = NULL;
            i->next = newnode;
      }
}



void List::printout()
{
      node *i=this->data;

      for( i=this->data; i != NULL; i=i->next )
            cout << "\t" << i->str << endl;
}



void List::sorting()                        // function sorts the linked list alphabetcially
{
      string tempStr;
      
      cout << "\n";

      for (node* temp = this->data; temp->next != NULL; temp = temp->next)
      {
            for (node* cursor = this->data->next; cursor->next != NULL; cursor=cursor->next)
            {
                  if (temp->str > cursor->str)
                  {
                        tempStr = temp->str;
                        temp->str = cursor->str;
                        cursor->str = tempStr;
                  }
            }
            cout<< tempStr << " " << endl;

      }
}



int List::sort()
{
      const int SIZE = 80;

      char text[3][SIZE], *temp, words[100][20]={""};

      int count[100]={0};
      
      cout << "\nEnter the sentence as shown above (case senstive); \n" << endl;

      for ( int i = 0; i <= 2; i++ )
            cin.getline ( &text [i][0], SIZE );
      
      for ( i = 0; i <= 2; i++ )
      
      {
            temp = strtok( &text [i][0], ". \n" );

            while (temp)
            {
                  for ( int j = 0; words[j][0] && strcmp(temp, &words[j][0]) != 0; j++ );  
                  ++count[j];
                        
                  if ( !words [j][0] )
                        strcpy( &words [j][0], temp );
                        
                  temp = strtok( NULL, ". \n" );
            }
      }
      
      cout.put( '\n' );

      cout<<" Word "<<"\t"<<"   Times found"<< "\t" << " File" <<endl;
      cout<<"________________________________"<<endl;

      for ( int j = 0; words [j][0] != '\0' && j <= 99; j++ )
      {
            cout << " " << &words[j][0] << "\t\t" << count[j] << "\t" << "test.txt"<<endl;      
      }

      cout<<"________________________________"<<endl;
      
      return 0;

}            




main(int argc, char *argv[])
{
      ofstream reportfile(argv[argc-1]);
      List *words = new List();
      string word;

      ifstream in("test.txt");  
   
      while(in >> word)                  // word is detected by white space
            words->add(word);

      cout<<"\n Words from file in order."<<endl;
      cout<<"____________________________\n"<<endl;

      words->printout();
      
      cout<<" \n "<<endl;

      words->sort();
      
      words->sorting();
      
      for (int q =1; q < argc -1; q++)                        //sends filenames to outputfile
      {
            reportfile << "From file : " << argv[q];
      }

      return 0;
}
      

0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8258878
You are reading in the words from the file, but then if you want to print them, then why are you using this loop:

>> for (int q =1; q < argc -1; q++)                    //sends filenames to outputfile
>> {
>>   reportfile << "From file : " << argv[q];
>> }

You alredy have a printout () function. You should call it like:

words -> printout () ;

(like you've done initially).

Now, if you want to write the words from the sorted linked list to the file, then you should not use the above for loop because it will run depending upon the number of command line arguments (argc) which you initially supplied when you executed the program (I guess if your program-name is MyProgram.cpp, then you called it as:

>MyProgram outputfile.txt

)

Now, this has nothing to do with the number of words in the linked-list. And moreover, you are writing argv[q] into the file, which will be a command line argument, not a word in the linked list. So you need to write another function which will write the linked list to the file. And you need to call only one fnuction for sorting, which is the sorting () function, not the sort () function at all. There is also an error in the for loop in the sorting () function, that the second (nested) for loop will have the condition cursor != NULL (instead of cursor -> next != NULL).

Here are some modifications in your code. You can try this:

#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std ;

struct node                                  
{
      string str ;                              
      node * next ;

} ; // structure definition over

class List
{
      node * data ; // private by default
public:
      List () : data ( NULL ) {} ; // default constructor ()
      List ( string item ) ;
      ~List () ;
      void add ( string item ) ;
      void printout () ;                    
      void sorting () ;
      void write_to_file ( char * ) ;

} ; // class definition over

List :: List ( string item )
{
      node * newnode = new node ;
      newnode -> str = item ;
      newnode -> next = NULL ;
      data = newnode ;

} // end of parameterized constructor ()

List :: ~List ()
{
      node * i ;
      node * temp = this -> data ;
     
      for ( i = this -> data -> next ; i -> next != NULL ; i = i -> next )
      {
            delete temp ;
            temp = i ;

      } // end for  

} // end of destructor ()

void List :: add ( string item )
{      
      node * newnode = new node ;
      newnode -> str = item ;
      newnode -> next = NULL ;

      if ( data == NULL )
            data = newnode ; // end if
     
      else
      {
            node * i ;

            for ( i = this -> data ; i -> next != NULL ; i = i -> next )
                  ; // end for
         
            i -> next = newnode ;
      } // end else

} // end of add ()

void List :: printout ()
{
      for ( node * i = this -> data ; i != NULL ; i = i -> next )
            cout << "\t" << i -> str << endl ; // end for

} // end of printout ()

void List :: sorting ()                    
{
      string tempStr ;

      for ( node * temp = this -> data ; temp -> next != NULL ; temp = temp -> next )
            for ( node * cursor = this -> data -> next ; cursor != NULL ; cursor = cursor -> next )
                  if ( temp -> str > cursor -> str )
                  {
                        tempStr = temp -> str ;
                        temp -> str = cursor -> str ;
                        cursor -> str = tempStr ;

                  } // end if, fors

} // end of sorting ()

void List :: write_to_file ( char * filename )
{
      ofstream reportfile ( filename ) ;
      
      for ( node * i = this -> data ; i != NULL ; i = i -> next )
            reportfile << i -> str << " " ; // end for

      reportfile.close () ;

} // end of write_to_file ()

int main ( int argc, char * argv [] )
{
      List * words = new List () ;
      string word ;
      ifstream in ( "test.txt" ) ;  
 
      while ( in >> word )
            words -> add ( word ) ; // end while

      in.close () ;

      cout << "\n Words from file in order: " << endl ;
      words -> printout () ;
     
      words -> sorting () ;

      cout << "\n Words after sorting: " << endl ;
      words -> printout () ;

      cout << "\n Writing to file: " << argv[argc-1] << " .... " ;
      words -> write_to_file ( argv[argc-1] ) ;
      cout << "\n Successfully written! " ;    
      return 0 ;

} // end of main ()


Hope that helps!

Mayank.
0
 

Author Comment

by:PALKTA
ID: 8260220
Mayank
this is good but the outcome of the sorting prints like this

aid
to
to
time
the
the
the
of
now
men
is
good
for
come
all
party

which is not in alphabetical order??
sorry about this taking so long!!!

PALKTA
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8260322
>> if ( temp -> str > cursor -> str )

Try this:

if ( strcmpi ( ( temp -> str ).c_str (), ( cursor -> str ).c_str () ) > 0 )


Mayank.

PS: If it doesn't work, plese post your entire current code and the input file contents too.
0
 

Author Comment

by:PALKTA
ID: 8268904

Mayank
My entire code and the input file contents is a simple sentence, at the moment i'm using

now is the time for all
good men to come to
the aid of the party

much appreciated

PALKTA

#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std;

struct node                                  
{
     string str;                              
     node * next;
};                                                                           // structure definition over



class List
{
private:
     node * data ;                                                       // private by default
public:    
     List () : data ( NULL ) {};                                        // default constructor ()
     List ( string item );
     ~List ();
     void add ( string item );
     void sorting ();
     void printout ( char * );
};                                                                           // class definition over
     


List :: List ( string item )
{
     node * newnode = new node;
    newnode -> str = item;
    newnode -> next = NULL;
    data = newnode;    
}                                                                           // end of parameterized constructor ()



List :: ~List ()
{
     node * i;
    node * temp = this -> data;
     
     for ( i = this -> data -> next ; i -> next != NULL ; i = i -> next )
     {
          delete temp;
          temp = i;
     }                                                                        
}                                                                           // end of destructor ()



void List :: add ( string item )
{    
     node * newnode = new node ;
    newnode -> str = item ;
    newnode -> next = NULL ;

     if ( data == NULL )
          data = newnode ;                                            
     
     else
     {
          node * i ;

          for ( i = this -> data ; i -> next != NULL ; i = i -> next );      
          {
               i -> next = newnode;
          }                                                                
     }                                                                      
}
                                             


void List :: sorting ()                    
{
     string tempStr;
     
     for ( node * temp = this -> data ; temp -> next != NULL ; temp = temp -> next )
     {
          for ( node * cursor = this -> data -> next ; cursor != NULL ; cursor = cursor -> next )
          {
               //if ( temp -> str > cursor -> str )
               if ( strcmpi ( ( temp -> str ).c_str (), ( cursor -> str ).c_str () ) > 0 )

               {
                    tempStr = temp -> str;
                    temp -> str = cursor -> str;
                    cursor -> str = tempStr;
               }                                                      
          }                                                                  
     }
}                                                                          



void List :: printout ( char * filename )
{
     ofstream reportfile ( filename );

     reportfile << "\nWords in alphabetical order." <<endl;
     reportfile << "____________________________" <<endl;

     for ( node * i = this -> data ; i != NULL ; i = i -> next )
     {
          reportfile << "\t \t" << i -> str << endl;
     }
}                                                                            




int main ( int argc, char * argv [] )
{
     List * words = new List ();
     string word;
     ifstream in ( "test.txt" );
     
     while ( in >> word )
          words -> add ( word );                                  

     in.close ();

    words -> sorting ();

     words -> printout ( argv[argc-1] );                    // Sends the list sorted to output file
         
     return 0;
}
 
0
 

Author Comment

by:PALKTA
ID: 8268926

Mayank

My entire code to date
the input file is simply a sentence and i am using

now is the time for all
good men to come to the
aid of the party

PALKTA


#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>

using namespace std;

struct node                                  
{
     string str;                              
     node * next;
};                                                                           // structure definition over



class List
{
private:
     node * data ;                                                       // private by default
public:    
     List () : data ( NULL ) {};                                        // default constructor ()
     List ( string item );
     ~List ();
     void add ( string item );
     void sorting ();
     void printout ( char * );
};                                                                           // class definition over
     


List :: List ( string item )
{
     node * newnode = new node;
    newnode -> str = item;
    newnode -> next = NULL;
    data = newnode;    
}                                                                           // end of parameterized constructor ()



List :: ~List ()
{
     node * i;
    node * temp = this -> data;
     
     for ( i = this -> data -> next ; i -> next != NULL ; i = i -> next )
     {
          delete temp;
          temp = i;
     }                                                                        
}                                                                           // end of destructor ()



void List :: add ( string item )
{    
     node * newnode = new node ;
    newnode -> str = item ;
    newnode -> next = NULL ;

     if ( data == NULL )
          data = newnode ;                                            
     
     else
     {
          node * i ;

          for ( i = this -> data ; i -> next != NULL ; i = i -> next );      
          {
               i -> next = newnode;
          }                                                                
     }                                                                      
}
                                             


void List :: sorting ()                    
{
     string tempStr;
     
     for ( node * temp = this -> data ; temp -> next != NULL ; temp = temp -> next )
     {
          for ( node * cursor = this -> data -> next ; cursor != NULL ; cursor = cursor -> next )
          {
               //if ( temp -> str > cursor -> str )
               if ( strcmpi ( ( temp -> str ).c_str (), ( cursor -> str ).c_str () ) > 0 )

               {
                    tempStr = temp -> str;
                    temp -> str = cursor -> str;
                    cursor -> str = tempStr;
               }                                                      
          }                                                                  
     }
}                                                                          



void List :: printout ( char * filename )
{
     ofstream reportfile ( filename );

     reportfile << "\nWords in alphabetical order." <<endl;
     reportfile << "____________________________" <<endl;

     for ( node * i = this -> data ; i != NULL ; i = i -> next )
     {
          reportfile << "\t \t" << i -> str << endl;
     }
}                                                                            




int main ( int argc, char * argv [] )
{
     List * words = new List ();
     string word;
     ifstream in ( "test.txt" );
     
     while ( in >> word )
          words -> add ( word );                                  

     in.close ();

    words -> sorting ();

     words -> printout ( argv[argc-1] );                    // Sends the list sorted to output file
         
     return 0;
}
 
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8269018
What is the output?
0
 

Author Comment

by:PALKTA
ID: 8283992
the output at current is

aid
to
to
time
the
the
the
of
now
men
is
good
for
come
all
party

but i need this printed out in alphabetical order like this

aid
all
come
for
good
is
men
now
of
party
the
the
the
time
to
to
0
 
LVL 30

Accepted Solution

by:
Mayank S earned 2000 total points
ID: 8284299
Try also to print the linked list initially (just after reading from the file) and check if it has been read properly. If it has been read properly, then there might be an error with the sorting.

Mayank.
0
 

Author Comment

by:PALKTA
ID: 8291212
Thanks Mayank
This code was important to me and i appreciate the effort you put into sorting my errors

Keep up the good work!!!!

PALKTA
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8291421
Glad to help :-)
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question