CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 17

Thread: wrong order

Threaded View

  1. #6
    Join Date
    Apr 2004
    Posts
    55

    Re: wrong order

    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).
    Last edited by BigEvil; April 6th, 2005 at 07:42 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured