Add a recursive readnum() function
Or instead of the recursive method, instead of adding the new node at the beginning of the list, add it at the end.Code:void linklist::readfile() { ifstream myFile("textfile.txt"); readnum(); myFile.close(); cout << "All the data has been read from the file." << '\n'; cout << "Press Enter to continue!" << '\n'; getch(); } void linklist::readnum() { if(myFile) { int s; myFile>>s; readnum(); this->additem(s); // Number read first will be added last } }
First one will be faster I guess, coz you won't have to traverse to the end of the list each time, but it will consume more memory (you can keep a pointer to end node in 2nd method, but it might make the code more complicated).Code:node *n = new node; n->info = number read from file; n->next = NULL; node *end = first; // first (or list) = pointer to beginning of the list if(end==NULL) // If list is empty first = n, end = n; else { while(end->next !=NULL) //Traverse to last node of list end = end->next; end->next = n; // Add new node after the last node }




Reply With Quote