Poh Sun
Poh Sun

Reputation: 75

C++ Link List error going to next node

I need to read words from a file and then put it into link list.
I have these codes here(below) which does the inserting into link list part.
The vector contains words I've read from a file

    List( vector <string> &v )
    {
        ListNode *cur = head;

        for ( int i = 0 ; i < v.size() ; i++ )
        {
            //cout << v[i] << endl;

            ListNode *newNode = new ListNode;

            newNode->item = v[i];

            if ( i == 0 )      // first node
            {
                newNode->next = NULL;
                head = newNode;
            }

            else               // insert node into the back
            {
                ListNode *prev = cur;
                newNode->next = prev->next;
                prev->next = newNode;
            }

            cout << cur->item << endl;

            system("pause");
        }
    }

My problem here is that my node doesn't go to the next node after inserting a word into a node.
I tried to put cur = cur->next; on between cout << cur->item << endl; and system("pause");
The program gives me error

Upvotes: 0

Views: 1158

Answers (1)

Mahesh
Mahesh

Reputation: 34625

You are not updating the child node correctly. Try this, in the else block.

else 
{
   ListNode *prev = cur;
   prev->next = newNode;
}
cur = newNode;

It can be rewritten even simpler. But first try to rectify the existing program and then go for an efficient one. Hope this helps !

Upvotes: 0

Related Questions