|
-
April 6th, 2005, 08:05 AM
#7
Re: wrong order
 Originally Posted by BigEvil
Add a recursive readnum() function
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
}
}
Or instead of the recursive method, instead of adding the new node at the beginning of the list, add it at the end.
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
}
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).
why reinventing the wheel? There is a std::vector, a std::list and a std::stack implementation...
http://msdn.microsoft.com/library/de...Stackstack.asp
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|